0
dt = data.table(a = rep(x = c(1, 2, 3), 3), y = as.numeric(1:9), z = as.numeric(2:10))

I know this summarizes the value by group for one column:

dt = data.table(a = rep(x = c(1, 2, 3), 3), y = as.numeric(1:9), z = as.numeric(2:10))

But if I try for multiple columns:

dt[, .(c('y', 'z') = list(mean(y) mean(z)), by = a]

I get the error

Error: unexpected '=' in "dt[, .(c('y', 'z') ="

What I'm looking for:

## data.table equivalent to
dt %>% group_by(a) %>% summarise(y = mean(y), z = mean(z))
#  a     y     z
#  <dbl> <dbl> <dbl>
#1     1     4     5
#2     2     5     6
#3     3     6     7
Rafael
  • 3,096
  • 1
  • 23
  • 61

1 Answers1

3
dt <- dt[, .(y = mean(y), z = mean(z)), by=.(a)]
Mr369
  • 384
  • 4
  • 17