我想讓最后一行滿足 a 中的條件data.table。
為此,我需要使用連接,因為這是迄今為止最快的方式。
mydt <- data.table(condition = c(F,F,T,F,F,T,F,F,F,F), row = 1:10).
> mydt
condition row
<lgcl> <int>
1: FALSE 1
2: FALSE 2
3: TRUE 3
4: FALSE 4
5: FALSE 5
6: TRUE 6
7: FALSE 7
8: FALSE 8
9: FALSE 9
10: FALSE 10
基本上我想要以前的rowwherecondition是 TRUE。這里的第六個元素應該是3,所有其余的 NA 。
我試圖通過 TRUE 和 FALSE 來計算它,因為由于某種原因我不能使用on = .(condition == T)
mydt[
mydt,
on = .(condition == condition, row < row),
.(result = row),
mult = "last"]$result
# [1] 1 2 3 4 5 6 7 8 9 10
# expected result: NA, 1, NA, 2, 4, 3, 5, 6, 7, 8, 9
# OR expected result (only for TRUE): NA, NA, NA, NA, NA, 3, NA, NA, NA, NA, NA
有什么幫助嗎?謝謝
編輯以下實作了預期的結果,dplyr但我仍在尋求data.table join解決方案
mydt %>% as.data.frame() %>% group_by(condition) %>% mutate(prev_result = lag(row))
condition row prev_result
<lgl> <int> <int>
1 FALSE 1 NA
2 FALSE 2 1
3 TRUE 3 NA
4 FALSE 4 2
5 FALSE 5 4
6 TRUE 6 3
7 FALSE 7 5
8 FALSE 8 7
9 FALSE 9 8
10 FALSE 10 9
uj5u.com熱心網友回復:
這是重現結果的一種方法data.table
mydt[, prev_results := shift(row, n=1, type="lag"), by = condition]
mydt
condition row prev_results
1: FALSE 1 NA
2: FALSE 2 1
3: TRUE 3 NA
4: FALSE 4 2
5: FALSE 5 4
6: TRUE 6 3
7: FALSE 7 5
8: FALSE 8 7
9: FALSE 9 8
10: FALSE 10 9
uj5u.com熱心網友回復:
你會想要保留x.row結果。默認情況下,您似乎得到了i.row。
library(data.table)
mydt <- data.table(condition = c(F, F, T, F, F, T, F, F, F, F), row = 1:10)
mydt[
mydt,
on = .(condition == condition, row < row),
mult = "last",
.(condition, i.row, x.row)
]
#> condition i.row x.row
#> 1: FALSE 1 NA
#> 2: FALSE 2 1
#> 3: TRUE 3 NA
#> 4: FALSE 4 2
#> 5: FALSE 5 4
#> 6: TRUE 6 3
#> 7: FALSE 7 5
#> 8: FALSE 8 7
#> 9: FALSE 9 8
#> 10: FALSE 10 9
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/522295.html
標籤:r加入数据表
上一篇:如何舍入一個值向量,以便舍入值的總和始終加起來為某個數字(此處為100)
下一篇:如何消除兩個圖例之間的巨大空間?
