Aggregating data.table with sum, length and grep

Viewed 325

Lets make a data.table:

dt <- data.table(x.1=1:8, x.2=1:8, x.3=2:9, vessel=rep(letters[1:2], each=4), Year=rep(2012:2015, 2))
dt
   x.1 x.2 x.3 vessel Year
1:   1   1   2      a 2012
2:   2   2   3      a 2013
3:   3   3   4      a 2014
4:   4   4   5      a 2015
5:   5   5   6      b 2012
6:   6   6   7      b 2013
7:   7   7   8      b 2014
8:   8   8   9      b 2015

I can aggregate it, using the functions length and sum, to get the sum of all x's in each year and the sum of unique vessels each year like this:

dt[, 
            list(
  x.1=sum(x.1),
  x.2=sum(x.2),
  x.3=sum(x.3),
  vessels=length(unique(vessel))),
    by=list(Year=Year)]

   Year x.1 x.2 x.3 vessels
1: 2012   6   6   8       2
2: 2013   8   8  10       2
3: 2014  10  10  12       2
4: 2015  12  12  14       2

This is what i want, but in my real data I have a lot of columns, so i would like to use grep or %like%, but i can not get it to work. I was thinking something in line with this:

dt[,grep("x",colnames(dt)),with = FALSE])

But how to merge that with the aggregate?

4 Answers
Related