我有一堆二进制变量,当变量为1时我想在列名中替换,否则为空。
数据框before
如下所示:
Apple Orange Banana
0 1 0
1 1 1
1 0 0
0 0 1
我想谈谈这个问题(after
):
Apple Orange Banana
NA Orange NA
Apple Orange Banana
Apple NA NA
NA NA Banana
我尝试过使用各种应用功能而没有运气。例如,我无法弄清楚为什么这段代码不起作用:
after <- apply(before,1,function(x) ifelse(x==1,colnames(x),NA))
答案 0 :(得分:3)
您也可以尝试
df[] <- names(df)[(NA^!df)+col(df)-1]
df
# Apple Orange Banana
#1 <NA> Orange <NA>
#2 Apple Orange Banana
#3 Apple <NA> <NA>
#4 <NA> <NA> Banana
df <- structure(list(Apple = c(0L, 1L, 1L, 0L), Orange = c(1L, 1L,
0L, 0L), Banana = c(0L, 1L, 0L, 1L)), .Names = c("Apple", "Orange",
"Banana"), class = "data.frame", row.names = c(NA, -4L))
答案 1 :(得分:2)
通过创建ifelse
apply
循环的情况下使用names
df[] <- ifelse(df == 1L, names(df)[col(df)], NA)
导致
# Apple Orange Banana
# 1 <NA> Orange <NA>
# 2 Apple Orange Banana
# 3 Apple <NA> <NA>
# 4 <NA> <NA> Banana
原始df
structure(list(Apple = c(0L, 1L, 1L, 0L), Orange = c(1L, 1L,
0L, 0L), Banana = c(0L, 1L, 0L, 1L)), .Names = c("Apple", "Orange",
"Banana"), class = "data.frame", row.names = c(NA, -4L))
答案 2 :(得分:2)
或者没有使用等级
的人df[] <- t(apply(df, 1, function(x){ifelse(x==1, names(x), NA)}))
Apple Orange Banana
1 <NA> Orange <NA>
2 Apple Orange Banana
3 Apple <NA> <NA>
4 <NA> <NA> Banana
答案 3 :(得分:0)
这个怎么样?
m[m == 1] <- rep(colnames(m), each = 4)[(m == 1)]
m[m == 0] <- NA
m
Apple Orange Banana
1 <NA> Orange <NA>
2 Apple Orange Banana
3 Apple <NA> <NA>
4 <NA> <NA> Banana