R Ifelse:查找是否有任何列满足条件 [英] R Ifelse: Find if any column meet the condition

查看:61
本文介绍了R Ifelse:查找是否有任何列满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对数组的多个列应用相同的条件,然后,如果任何列满足条件,则创建一个新列.

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.

我可以使用OR语句手动完成此操作,但我想知道是否有一种简单的方法将其应用于更多列.

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.

一个例子:

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)

但是它考虑所有数据集的条件,而不是按行,因此所有行都被赋予1.

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

推荐答案

我们可以对 lapply

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

这篇关于R Ifelse:查找是否有任何列满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆