Reputation: 12515
df <- data.frame(col1 = rep(1, 15),
col2 = rep(2, 15),
col3 = rep(3, 15),
group = c(rep("A", 5), rep("B", 5), rep("C", 5)))
for(col in c("col1", "col2", "col3")){
filt.df <- df %>%
filter(group == "A") %>%
select(group, col)
# do other things, like ggplotting
}
Error: All select() inputs must resolve to integer column positions. The following do not: * col
How can I iterate through a specific vector of columns using dplyr
? I know I would use something like df[[col]]
in base
R, but am unfamiliar with how to do it in dplyr
.
Upvotes: 2
Views: 6363
Reputation: 1863
select_
and other underscore alternatives are now depreciated in dplyr. One should now use select(group, .data[[col]])
. See the programming
vignette in dplyr help for more.
Upvotes: 2
Reputation: 6020
this should work. I use the select_() function
library(dplyr)
df <- data.frame(col1 = rep(1, 15),
col2 = rep(2, 15),
col3 = rep(3, 15),
group = c(rep("A", 5), rep("B", 5), rep("C", 5)))
for(col in c("col1", "col2", "col3")){
filt.df <- df %>%
filter(group == "A") %>%
select_(.dots = c('group', col))
# do other things, like ggplotting
print(filt.df)
}
Upvotes: 5