我们可以使用set,这样会更有效率
for(j in 2:4) {
set(DT, i = which(DT[[j]]==4), j=j, value = 10)
}
DT
# V1 V2 V3 V4
#1: A 2 2 10
#2: B 1 10 10
#3: C 3 10 3
#4: D 3 2 10
#5: E 3 3 3
#6: F 10 3 3
上面的也可以用列名来完成
for(j in names(DT)[2:4]){
set(DT, i = which(DT[[j]]==4), j=j, value = 10)
}
或者另一种选择是使用感兴趣的列(数字索引或列名)指定.SDcols,循环遍历Data.table 的子集(.SD),replace 的值是4 到 10 并将 (:=) 输出分配回感兴趣的列
DT[, (2:4) := lapply(.SD, function(x) replace(x, x==4, 10)), .SDcols = 2:4]
或使用列名
DT[, (names(DT)[2:4]) := lapply(.SD, function(x) replace(x, x==4, 10)),
.SDcols = names(DT)[2:4]]
数据
set.seed(24)
DT <- data.table(V1 = LETTERS[1:6], V2 = sample(1:4, 6, replace = TRUE),
V3 = sample(2:4, 6, replace = TRUE), V4 = sample(3:4, 6, replace= TRUE))