2016-12-10 79 views
-1

我想找到一種方法將所有邏輯列強制轉換爲一列,並將列標題作爲因子。將多個TRUE/FALSE列合併爲一個

下面是一個例子:

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 

任何幫助將不勝感激!

回答

3

我們可以使用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

您可以重塑從廣角到長數據,然後就變成了標準的子集操作

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