'How do I use map to drop a variable from a list of data frames
How do I drop a variable with the same name in a list of dataframes using map? Sadly the variable appears in a different position in each data frame, so I can't drop it using its position. It has to be with its name.
var1<-rnorm(100)
var2<-sample(letters, 100, replace=T)
var3<-rnorm(100)
df<-data.frame(var1, var2, var3)
df2<-data.frame(var1, var3, var2)
list1<-list(df, df2)
library(purrr)
#This works, but it won't help me because var2 is in different positions.
list1 %>%
map(., `[`, -2)
#This does not work.
list1 %>%
map(., `[`, -c("var2"))
Solution 1:[1]
You can do
map(list1, ~ .x %>% select(-var2))
Or using NSE with a curly-curly expression
name_excl <- "var2"
map(list1, ~ .x %>% select(-{{name_excl}}))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maurits Evers |
