[R] ifelse for creating discriminating variable based on two conditions
Andreas Nord
andreas.nord at biol.lu.se
Fri Oct 14 08:17:21 CEST 2016
Dear list,
Apologies for a likely naive question.
I am trying to create a discriminating dummy variable using 'ifelse' based on conditions in two variables.
Specifically, I want to assign levels in a new factor as '0' or '1' based on a user-defined cut off. I.e. something similar to:
>data1<-data.frame(molecule=runif(30,min=0,max=1e3))
>data1$newcol<-ifelse(data1$molecule>2*sd(data1$molecule),1,0)
Which is all straightforward.
But how do I go on to assign values in variable 'molecule'based on the same cut off, but separately for each level of a second variable, in this case the factor 'fruit' with three levels. That is, how do I derive fruit-specific cut-offs using a data frame with the general structure of that below?
>data2<-data.frame(molecule=runif(30,min=0,max=1e3),fruit=factor(rep(c('apple','pear','orange'),10)))
Many thanks in advance!
[[alternative HTML version deleted]]
More information about the R-help
mailing list