not_a_robot not_a_robot - 2 months ago 16
R Question

Iterate through columns in 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(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
.

Answer

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)
}
Comments