Reputation: 403
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
Reputation: 886938
Using dplyr
library(dplyr)
df %>%
summarise(across(everything(), any))
# A B C
#1 TRUE TRUE FALSE
Upvotes: 1
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