[英]rowMean based on multiple conditions
I want to calculate a rowMean across two columns if the conditions below are met. 如果要满足以下条件,我想跨两列计算rowMean。 If not return NA.
如果没有返回NA。
This is how I would write it in Excel. 这就是我在Excel中编写它的方式。 Can anyone suggest how I might do this in R?
谁能建议我该怎么做?
=IF(OR(AND(V1>=3,V2>=0),AND(V1>=2,V2>=1),AND(V1>=1,V2>=2)),(V3+V4)/(V5+V6),NA)
I've written basic If statements in R, but can't visualise this other than writing it as above. 我已经在R中编写了基本的If语句,但是除了如上所述编写它之外,无法对其进行可视化。
If a is your data.frame and you want to use a loop: 如果a是您的data.frame,并且您想使用循环:
for(i in 1:nrow(a)){
a$results[i] <- ifelse( (a[i,1]>=3 & a[i,2]>=0) | (a[i,1] >=2 & a[i,2] >= 1) | ..., mean(a[i,1],a[i,2]), NA) # & is the AND | is the OR
}
The better way would be to define a function for the job and use apply to loop through the data.frame. 更好的方法是为作业定义一个函数,然后使用apply遍历data.frame。
f <- function(x){
ifelse((x[1]>=3 & x[2]>=0) | (x[1] >=2 & x[2] >= 1) | ..., mean(x[1],x[2]), NA)
}
a$results <- apply(a,1,f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.