jeudi 6 septembre 2018

use if else statement inside apply function in R

I have following 2 columns

lower=rnorm(10,0,1)
upper=rnorm(10,1,1)

dd=data.frame(lower,upper)

i wanted to know whether for each row , lower < 0.5 and upper > 1. I did it using a for loop as follows,

cc=c()
for(i in 1: 10 ){
  cc[i]= ifelse(  (  dd$upper[i] > 1 && dd$lower[i] < 0.5  ),1,0
  )
}

But i wanted to do this using one of the suitable apply function. Since the data is in a data frame, i tried using apply function . This is my code,

apply(dd , 1, function (i,j) {ifelse( (dd$i> 0.5 && dd$j<0.5) ,0,1 )

}
  )

I am getting NA 's. It is really helpful if someone help me figure out the mistake

Thank you

Aucun commentaire:

Enregistrer un commentaire