【发布时间】:2019-01-08 12:28:56
【问题描述】:
我有一个包含两列的数据表:“id”和“prevId”。我想找到其中一行的“prevId”值等于后面一行的“id”值的所有实例。然后我想交换数据表中这些行的顺序。
到目前为止,我已经尝试过使用以下逻辑:
data[, index:=.I]
data[, priorMatch:=index[1L], by = cumsum(prevId == id)]
apply(records, 1, FUN = function(x) {
if (!is.na(priorMatch)) {
records[x[["index"]],] <- records[x[["index"]] - 1,]
records[x[["index"]] - 1,] <- x
}
})
但是,cumsum() 实际上并没有将“prevId”等同于当前行的“id”的最早的前一行获取。
期望结果的示例:
id prevId
ef cd
cd ab
将被转换为:
id prevId
cd ab
ef cd
感谢您提供任何帮助。谢谢!
【问题讨论】:
-
请通过粘贴
dput()的内容提供输入data
标签: r data.table