假设我有:
x = data.table( id=c(1,1,1,2,2,2), price=c(100,110,120,200,200,220) )
> x
id price
1: 1 100
2: 1 110
3: 1 120
4: 2 200
5: 2 200
6: 2 220
Run Code Online (Sandbox Code Playgroud)
并希望在省略当前行后为每行找到组中最便宜的价格 (by=id)。所以结果应该是这样的:
> x
id price cheapest_in_this_id_omitting_current_row
1: 1 100 110 # if I take this row out the cheapest is the next row
2: 1 110 100 # row 1
3: 1 120 100 # row 1
4: 2 200 200 # row 5
5: 2 200 200 # row 4 (or 5)
6: 2 220 200 # row 4 (or 5)
Run Code Online (Sandbox Code Playgroud)
所以就像使用:
x[, cheapest_by_id := min(price), id]
Run Code Online (Sandbox Code Playgroud)
但删除每个计算的当前行。
如果我可以有一个引用组内当前行的变量(如 .row_nb),我将使用:
x[, min(price[-.row_nb]), id]
Run Code Online (Sandbox Code Playgroud)
但是这个.row_nb似乎不存在...?
我们按“id”分组,combn在行序列上使用,指定要选择的元素数量,即“m”为比行数少 1 ( .N-1),使用输出作为combn数字索引来对“价格”进行子集化,获取min并将输出分配 ( :=) 作为新列。
x[, cheapest_in_this_id_omitting_current_row:=
combn(.N:1, .N-1, FUN=function(i) min(price[i])), by = id]
x
# id price cheapest_in_this_id_omitting_current_row
#1: 1 100 110
#2: 1 110 100
#3: 1 120 100
#4: 2 200 200
#5: 2 200 200
#6: 2 220 200
Run Code Online (Sandbox Code Playgroud)
或者,我们可以不使用combn,而是循环序列,使用它来索引“价格”,获取mean. 我想这会很快。
x[,cheapest_in_this_id_omitting_current_row:=
unlist(lapply(1:.N, function(i) min(price[-i]))) , id]
Run Code Online (Sandbox Code Playgroud)