R Ifelse: Find if any column meet the condition

北慕城南 提交于 2021-01-28 17:53:36

问题


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.


回答1:


We can use Reduce with lapply

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/60572483/r-ifelse-find-if-any-column-meet-the-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!