我有一个与此问题相关的问题,我之前曾问过:从foreach循环中赋值.我发现尽管友好用户提供的解决方案指向了正确的方向,但它们并没有解决我的实际问题.这里是示例数据集:
td <- data.table(date=c(rep(1,10),rep(2,10)),var=c(rep(1,4),2,rep(1,5)),id=rep(1:10,2))
Run Code Online (Sandbox Code Playgroud)
它与以前相同,但它更好地反映了我的真实数据我想用文字做什么:对于每个id,我想在一定时期内得到所有其他id的均值(例如mean(td [date =="2004] -01-01"&id!= 1] $ var)但是适用于所有期间和所有ID).所以它是某种嵌套操作.我试过这样的事情:
td[,.SD[,mean(.SD$var[-.I]),by=id],by=date]
Run Code Online (Sandbox Code Playgroud)
但这并没有给出正确的结果.
Josh very intelligently suggested to use `.BY ` instead of `.GRP`
td[, td[!.BY, mean(var), by=date], by=id]
Run Code Online (Sandbox Code Playgroud)
如果按键,id可以.GRP按以下方式使用:
setkey(td, id)
## grab all the unique IDs. Only necessary if not all ids are
## represented in all dates
uid <- unique(td$id)
td[, td[!.(uid[.GRP]), mean(var), by=date] , by=id]
id date V1
1: 1 1 1.111111
2: 1 2 1.111111
3: 2 1 1.111111
4: 2 2 1.111111
5: 3 1 1.111111
6: 3 2 1.111111
7: 4 1 1.111111
8: 4 2 1.111111
9: 5 1 1.000000
10: 5 2 1.000000
11: 6 1 1.111111
12: 6 2 1.111111
13: 7 1 1.111111
14: 7 2 1.111111
15: 8 1 1.111111
16: 8 2 1.111111
17: 9 1 1.111111
18: 9 2 1.111111
19: 10 1 1.111111
20: 10 2 1.111111
Run Code Online (Sandbox Code Playgroud)