【发布时间】:2019-11-25 19:33:40
【问题描述】:
我有一些长格式的数据,
library(data.table)
dat <- data.table(id=1:12, group=rep(1:2, each=6), time=c(rep(9:8, each=3),rep(6:7, each=3)), measure=1:3)
> dat
id group time measure
1: 1 1 9 1
2: 2 1 9 2
3: 3 1 9 3
4: 4 1 8 1
5: 5 1 8 2
6: 6 1 8 3
7: 7 2 6 1
8: 8 2 6 2
9: 9 2 6 3
10: 10 2 7 1
11: 11 2 7 2
12: 12 2 7 3
我想创建一个新变量,在每个group 中给出time 的索引。也就是说,期望的输出是
> res
id group time measure index
1: 1 1 9 1 2
2: 2 1 9 2 2
3: 3 1 9 3 2
4: 4 1 8 1 1
5: 5 1 8 2 1
6: 6 1 8 3 1
7: 7 2 6 1 1
8: 8 2 6 2 1
9: 9 2 6 3 1
10: 10 2 7 1 2
11: 11 2 7 2 2
12: 12 2 7 3 2
如果每个组内每次只有一行(即没有measure 变量),我会按照以下方式做一些事情
dat[order(group,time), .(index=seq_len(.N)), by=.(group)]
但在这种情况下,我不知所措。
【问题讨论】:
标签: r indexing data.table