我有以下data.table
df <- data.table(
id = c(rep(1,6),rep(2,6),rep(3,6)),
grp = c(rep("x",6),rep("y",6),rep("z",6)),
val1 = 1:18,
val2 = 13:30
)
我要两个按行条件应用两个不同函数例如:
cols <- paste0("val",1:2)
df[id == 1,lapply(.SD, function (x) tail(x,2)),.SDcols = cols,by = list(id,grp)]
df[id != 2,lapply(.SD, function (x) tail(x,3)),.SDcols = cols,by = list(id,grp)]
我对使用data.table
很陌生,所以可能有比进行单独的计算然后将上面的两个表连接起来更有效的方法
这里是另一种选择:
df[.N:1L, ri := rowid(id, grp)]
#for the first, df[id == 1L, tail(.SD, 2L), .(id, grp), .SDcols = cols]
df[id == 1L & ri <= 2L]
# id grp val1 val2 ri
#1: 1 x 5 17 2
#2: 1 x 6 18 1
#and for df[id != 2, tail(.SD, 3L), .(id,grp), .SDcols = cols]
df[id != 2L & ri <= 3L]
# id grp val1 val2 ri
#1: 1 x 4 16 3
#2: 1 x 5 17 2
#3: 1 x 6 18 1
#4: 3 z 16 28 3
#5: 3 z 17 29 2
#6: 3 z 18 30 1
希望了解您的数据集的大小和加速。