-2

m is a list of 2 as shown below:

   [[1]]
     [,1]      [,2]    
[1,] "a"        "b"

[[2]]
     [,1]     
[1,] "a"
[2,] "b"

Now I need to use these sub lists in my group_by_at function, such that there are 3 group by(s): (1): by a, (2): by b, and (3) by "a & b". I have been constantly failing to achieve this. group_by_at function gives me error: must evaluate to column positions or names, not a list. Any help will be greatly appreciated.

Thanks!

Stats
  • 97
  • 7
  • 2
    It's hard to know how to help without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), i.e. data in the format you're using and the code that isn't working. If the `group_by` functions you're using are from `dplyr`, those should be called on data frames, not lists. Take a look back through the arguments specified in the docs of those functions – camille Nov 06 '19 at 14:26
  • Thanks @camille. What else can I use if I need to group_by variables that are present within a list?? TIA – Stats Nov 06 '19 at 17:17
  • Without your data or code, all I could do is guess, which ultimately isn't very helpful – camille Nov 06 '19 at 17:58

1 Answers1

0

Here is one way which might work.

library(dplyr)
library(purrr)

map(m, function(x) map(seq(ncol(x)), function(y) 
       df %>% group_by_at(x[,y]) %>% summarise(sum = sum(c))))


#[[1]]
#[[1]][[1]]
# A tibble: 1 x 2
#      a   sum
#  <dbl> <int>
#1     1    15

#[[1]][[2]]
# A tibble: 2 x 2
#      b   sum
#  <dbl> <int>
#1     1     6
#2     2     9


#[[2]]
#[[2]][[1]]
# A tibble: 2 x 3
# Groups:   a [1]
#      a     b   sum
#  <dbl> <dbl> <int>
#1     1     1     6
#2     1     2     9

data

Using it on this sample data

m <- list(matrix(c("a", "b"), ncol = 2), matrix(c("a", "b")))
df <- data.frame(a = 1, b = c(1, 1, 1, 2, 2), c = 1:5)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213