Question

I want to calculate a rowMean across two columns if the conditions below are met. If not return NA.

This is how I would write it in 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.

Was it helpful?

Solution

If a is your data.frame and you want to use a loop:

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.

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top