Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

r - How to group data.table by multiple columns?

I'm using the data.table package to speed up some summary statistic collection on a data set.

I'm curious if there's a way to group by more than one column. My data looks like this:

  purchaseAmt        adShown        url
   15.54            00001         150000001
    4.82            00002         150000001
  157.99            05005         776300044
   ...               ...            ...

I can do something like this:

adShownMedian <- df1[,median(purchaseAmt),by="adShown"]

to get each ad's median. How would I do something that combines adShown and url?

I've tried this:

adShownMedian <- df1[,median(purchaseAmt),by=c("adShown","url")]

but no luck.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use by=list(adShown,url) instead of by=c("adShown","url")

Example:

set.seed(007) 
DF <- data.frame(X=1:20, Y=sample(c(0,1), 20, TRUE), Z=sample(0:5, 20, TRUE))

library(data.table)
DT <- data.table(DF)
DT[, Mean:=mean(X), by=list(Y, Z)]


     X Y Z      Mean
 1:  1 1 3  1.000000
 2:  2 0 1  9.333333
 3:  3 0 5  7.400000
 4:  4 0 5  7.400000
 5:  5 0 5  7.400000
 6:  6 1 0  6.000000
 7:  7 0 3  7.000000
 8:  8 1 2 12.500000
 9:  9 0 5  7.400000
10: 10 0 2 15.000000
11: 11 0 4 14.500000
12: 12 0 1  9.333333
13: 13 1 1 13.000000
14: 14 0 1  9.333333
15: 15 0 2 15.000000
16: 16 0 5  7.400000
17: 17 1 2 12.500000
18: 18 0 4 14.500000
19: 19 1 5 19.000000
20: 20 0 2 15.000000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...