Dhwani Dholakia
Dhwani Dholakia

Reputation: 191

Error in dplyr function

form_name = [1] "abc.A"    "abc.A.1"  "abc.B"    "abc.B.1"  "abc.DR"   "abc.DR.1"

library(dplyr)
dd <- list(NULL)
for(i in form_name){
dd[[i]] <- ka %>% group_by(i) %>% summarise(n= n())
}

When i apply loop over dplyr function it says

Error: unknown column 'i'

Upvotes: 3

Views: 432

Answers (1)

akrun
akrun

Reputation: 887118

We can use group_by_(.dots=i). We create a NULL list ('dd') and set the names as 'form_name', then loop through the 'form_name', and change the group_by as mentioned above.

dd <- setNames(vector('list', length= length(form_name)), form_name)
for(i in form_name){
  dd[[i]] <- ka %>%
                 group_by_(.dots=i) %>%
                 summarise(n=n())
}

dd
#$abc.A
#Source: local data frame [3 x 2]

#   abc.A     n
#  (fctr) (int)
#1      A     2
#2      B     2
#3      C     2

#$abc.B
#Source: local data frame [2 x 2]

#   abc.B     n
#  (fctr) (int)
#1      D     3
#2      E     3

data

form_name <- c('abc.A', 'abc.B')
ka <- data.frame(abc.A= rep(LETTERS[1:3], 2), 
                   abc.B= rep(LETTERS[4:5], each=3))

Upvotes: 4

Related Questions