你可能会从Kaggle认出这一点。我有多个名为Soil_Type1的列,一直到Soil_Type40。如果土壤类型不存在,则值为0;如果存在,则为1。每行只能有1种土壤类型。
我想创建一个新的列,如果Soil_Type1 = 1则取值S1,如果Soil_Type2 = 1则取S2。我可以做暴力,即每次行。有没有办法循环呢?
train_raw[,16:53 := lapply(.SD, as.character), .SDcols =16:53 ]
train_raw[,Soil_Type := "" ]
train_raw[Soil_Type1 == 1, Soil_Type := "S1"]
train_raw[Soil_Type2 == 1, Soil_Type := "S2"]
train_raw[Soil_Type3 == 1, Soil_Type := "S3"]
train_raw[Soil_Type4 == 1, Soil_Type := "S4"]
修改
对不起,这是一个可重现的例子的意思吗?
train_raw <- data.table(Soil_Type = "",
Soil_Type1 = c(0,0,0,1),
Soil_Type2 = c(0,0,1,0),
Soil_Type3 = c(1,1,0,0))
train_raw[,Soil_Type := "" ]
答案 0 :(得分:1)
感谢David Arenburg回答。
train_raw[, Soil_Type := "" ]
indx <- which(names(train_raw) == "Soil_Type")
cols <- paste0("Soil_Type", 1:4)
for(j in 1:length(cols))
set(train_raw,which(train_raw[[cols[j]]] == 1L),
j = indx, value = paste0("S", j))