按列名替换列条目

时间:2016-11-24 12:39:37

标签: r dataframe replace data.table

我想用data.table或data.frame替换其列名中的值(即“x”)。

示例:

# sample data
Substance <- LETTERS[1:10]
Jan10 <- c("x","x",NA,NA,NA,"x","x","x","x",NA)
Apr10 <- c("x",NA,"x",NA,"x","x","x","x",NA,"x")
Jul10 <- c(NA,NA,NA,"x","x","x","x",NA,"x","x")
Oct10 <- c("x","x","x","x",NA,"x",NA,"x",NA,"x")

dt <- as.data.table(cbind(Substance, Jan10, Apr10, Jul10, Oct10))

# manually changing one column
dt[Jan10=="x", Jan10 := "Jan10"]

目标:所有列应该看起来像更改的Jan10列。如何用相应的列名替换每列中的“x”值?谢谢你的任何建议。

1 个答案:

答案 0 :(得分:1)

我们遍历列,使用set将NA值替换为列名

for(j in 2:ncol(dt)){
    set(dt, i=which(dt[[j]]=="x"), j=j, value = names(dt)[j])
 }

dt
#    Substance Jan10 Apr10 Jul10 Oct10
# 1:         A Jan10 Apr10    NA Oct10
# 2:         B Jan10    NA    NA Oct10
# 3:         C    NA Apr10    NA Oct10
# 4:         D    NA    NA Jul10 Oct10
# 5:         E    NA Apr10 Jul10    NA
# 6:         F Jan10 Apr10 Jul10 Oct10
# 7:         G Jan10 Apr10 Jul10    NA
# 8:         H Jan10 Apr10    NA Oct10
# 9:         I Jan10    NA Jul10    NA
#10:         J    NA Apr10 Jul10 Oct10