R Ifelse: Find if any column meet the condition

Viewed 779

I'm trying to apply the same condition for multiple columns of an array and, then, create a new column if any of the columns meet the condition.

I can do it manually with an OR statement, but I was wondering if there is an easy way to apply it for more columns.

An example:

data <- data.frame(V1=c("A","B"),V2=c("A","A","A","B","B","B"),V3=c("A","A","B","B","A","A"))
data[4] <- ifelse((data[1]=="A"|data[2]=="A"|data[3]=="A"),1,0)

So the 4th row is the only that doesn't meet the condition for all columns:

  V1 V2 V3 V1
1  A  A  A  1
2  B  A  A  1
3  A  A  B  1
4  B  B  B  0
5  A  B  A  1
6  B  B  A  1

Do you know a way to apply the condition in a shorter code? I tried something like

data[4] <- ifelse(any(data[,c(1:3)]=="A"),1,0)

but it consider the condition for all the dataset instead of by rows, so all the rows are given 1.

3 Answers

We can use Reduce with lapply

data$NewCol <- +( Reduce(`|`, lapply(data, `==`, 'A')))

We can use apply row-wise :

data$ans <- +(apply(data[1:3] == "A", 1, any))
data

#  V1 V2 V3 ans
#1  A  A  A   1
#2  B  A  A   1
#3  A  A  B   1
#4  B  B  B   0
#5  A  B  A   1
#6  B  B  A   1

Try:

data$V4 <- +(rowSums(data == 'A') > 0)

Output:

  V1 V2 V3 V4
1  A  A  A  1
2  B  A  A  1
3  A  A  B  1
4  B  B  B  0
5  A  B  A  1
6  B  B  A  1
Related