[英]R Ifelse: Find if any column meet the condition
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.我可以用 OR 语句手动完成,但我想知道是否有一种简单的方法可以将它应用于更多列。
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:所以第 4 行是唯一不满足所有列条件的行:
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。
我们可以将Reduce
与lapply
一起lapply
data$NewCol <- +( Reduce(`|`, lapply(data, `==`, 'A')))
We can use apply
row-wise :我们可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.