purple_plop
purple_plop

Reputation: 280

If Value Exists in Any Column for a Row Automatically Flag Whole Row R

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

Answers (2)

akrun
akrun

Reputation: 887048

We can use any with apply

df$has_1 <- apply(df, 1, any)

data

df <- data.frame(a = c(0, 0, 1, 0, 1), b = 0, c = c(0, 1, 0, 0, 1))

Upvotes: 0

Ronak Shah
Ronak Shah

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

Related Questions