Reputation: 280
I subset my dataframe to include many variables and if a row contains a value of 1 for any column, I need to flag that row. What is a nice way to do this?
Upvotes: 0
Views: 323
Reputation: 887048
We can use any
with apply
df$has_1 <- apply(df, 1, any)
df <- data.frame(a = c(0, 0, 1, 0, 1), b = 0, c = c(0, 1, 0, 0, 1))
Upvotes: 0
Reputation: 388907
You could use rowSums
:
df$has_1 <- rowSums(df == 1, na.rm = TRUE) > 0
df
# a b c has_1
#1 0 0 0 FALSE
#2 0 0 1 TRUE
#3 1 0 0 TRUE
#4 0 0 0 FALSE
#5 1 0 1 TRUE
data
df <- data.frame(a = c(0, 0, 1, 0, 1), b = 0, c = c(0, 1, 0, 0, 1))
Upvotes: 3