kin182
kin182

Reputation: 403

How to collapse rows based on conditions of columns?

I have a df like

df = data.frame("A" = c(TRUE,FALSE,FALSE,FALSE),
                "B" = c(FALSE,TRUE,TRUE,FALSE),
                "C" = c(FALSE,FALSE,FALSE,FALSE))

I wanted to collapse to only one row if there is at least one "TRUE" per column, like

      A     B     C
1  TRUE  TRUE FALSE

I wonder how we do it? Thanks!

Upvotes: 1

Views: 113

Answers (3)

akrun
akrun

Reputation: 886938

Using dplyr

library(dplyr)
df %>%
    summarise(across(everything(), any))
#     A    B     C
#1 TRUE TRUE FALSE

Upvotes: 1

Duck
Duck

Reputation: 39585

Maybe apply() can be useful:

#Data
df = data.frame("A" = c("TRUE","FALSE","FALSE","FALSE"),
                "B" = c("FALSE","TRUE","TRUE","FALSE"),
                "C" = c("FALSE","FALSE","FALSE","FALSE"))
#Apply
apply(df,2,function(x) any(x=='TRUE'))

Output:

    A     B     C 
 TRUE  TRUE FALSE 

Or setting logical values:

#Data 2
df = data.frame("A" = c(TRUE,FALSE,FALSE,FALSE),
                "B" = c(FALSE,TRUE,TRUE,FALSE),
                "C" = c(FALSE,FALSE,FALSE,FALSE))
#Apply
apply(df,2,function(x) any(x==TRUE))

Output:

    A     B     C 
 TRUE  TRUE FALSE 

Upvotes: 2

tmfmnk
tmfmnk

Reputation: 39858

You can do:

colSums(df) != 0

    A     B     C 
 TRUE  TRUE FALSE

Upvotes: 3

Related Questions