2
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.

Sotos
  • 51,121
  • 6
  • 32
  • 66
blacksite
  • 12,086
  • 10
  • 64
  • 109
  • So you want a list with group A & col1, group A & col2, group A & col3, group B & col1, etc...? – Sotos Oct 03 '16 at 14:22
  • Yes. In my real data, `col1`, `col2`, and `col3` are difference vectors that I want to make different charts for. – blacksite Oct 03 '16 at 14:30

2 Answers2

5

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)
}
Wietze314
  • 5,942
  • 2
  • 21
  • 40
2

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.

dez93_2000
  • 1,730
  • 2
  • 23
  • 34