如何循环浏览文件中的所有变量?我在下面有一个示例代码。我的数据集命名为dt。
library(data.table)
dt <- data.table(df)
#Flagging each group of 1 and successive 2s uniquely
dt[,flag := 0]
dt[classobj == 1,flag := 1]
dt[,flag := cumsum(flag)]
如何让下面的代码集循环遍历所有变量?我得到了大约500多个变量,并且它可以手动完成。
#Copying down the value of valtype = 1 to all other rows with the same flag
dt[,var1 := .SD[classobj == 1, var1], by = "flag"]
dt[,var2 := .SD[classobj == 1, var2], by = "flag"]
...
dt[,varN := .SD[classobj == 1, varN], by = "flag"]
答案 0 :(得分:0)
沿着这些方向应该做的事情 -
dt[
,
setdiff(colnames(dt),c("flag","classobj")) :=
.SD[
classobj == 1,
setdiff(colnames(dt),c("flag","classobj")),
with = FALSE
],
by = "flag"
]