Caleb Lam
Caleb Lam

Reputation: 111

merge multiple TRUE/FALSE columns into one

I want to find a way to coerce all the logical columns into a single column with the column titles as factors.

Here is an example:

  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

Desired Output:

Eviction.ID             Reason 
1     M162268       Non.Payment 
2     M161957          Nuisance 
3     M162256       Non.Payment 
4     M162135            Breach 
5     M161901          Nuisance 
6     M162428       Illegal.Use

Any help would be greatly appreciated!

Upvotes: 0

Views: 1770

Answers (2)

SymbolixAU
SymbolixAU

Reputation: 26248

You can reshape the data from wide to long, then it becomes a standard subsetting operation

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

Upvotes: 2

akrun
akrun

Reputation: 887048

We can use max.col to get the index of the max value (here it is TRUE) in each row, get the corresponding column names based on that index and cbind with the first column.

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

Upvotes: 4

Related Questions