我想找到一种方法将所有逻辑列强制转换为单个列,并将列标题作为因子。
以下是一个例子:
Eviction.ID Non.Payment Breach Nuisance Illegal.Use
1 M162268 TRUE FALSE FALSE FALSE
2 M161957 FALSE FALSE TRUE FALSE
3 M162256 TRUE FALSE FALSE FALSE
4 M162135 FALSE TRUE FALSE FALSE
5 M161901 FALSE FALSE TRUE FALSE
6 M162428 FALSE FALSE FALSE TRUE
期望的输出:
Eviction.ID Reason
1 M162268 Non.Payment
2 M161957 Nuisance
3 M162256 Non.Payment
4 M162135 Breach
5 M161901 Nuisance
6 M162428 Illegal.Use
非常感谢任何帮助!
答案 0 :(得分:4)
我们可以使用max.col
获取每行中max
值的索引(此处为TRUE),根据该索引获取相应的列名称,并使用cbind
获取第一栏。
cbind(df1[1], Reason= names(df1)[max.col(df1[-1], "first")+1])
# Eviction.ID Reason
#1 M162268 Non.Payment
#2 M161957 Nuisance
#3 M162256 Non.Payment
#4 M162135 Breach
#5 M161901 Nuisance
#6 M162428 Illegal.Use
答案 1 :(得分:2)
您可以将数据从宽到长整形,然后它成为标准子集操作
library(reshape2)
## melt from wide to long
df <- melt(df, "Eviction.ID", variable.name = "Reason")
## subset on TRUE values/rows, and keep the columns of interest
df[df$value == TRUE, c("Eviction.ID", "Reason")]
# Eviction.ID Reason
# 1 M162268 Non.Payment
# 3 M162256 Non.Payment
# 10 M162135 Breach
# 14 M161957 Nuisance
# 17 M161901 Nuisance
# 24 M162428 Illegal.Use