[R] ifelse for creating discriminating variable based on two conditions

Jim Lemon drjimlemon at gmail.com
Fri Oct 14 10:50:40 CEST 2016


Hi Andreas,
Try this:

fruit_2sds<-by(data2$molecule,data2$fruit,sd)*2
data2$newcol<-ifelse(data2$molecule>fruit_2sds[data2$fruit],1,0)

or even just:

data$newcol<-as.numeric(data2$molecule>fruit_2sds[data2$fruit])

Jim


On Fri, Oct 14, 2016 at 5:17 PM, Andreas Nord <andreas.nord at biol.lu.se> wrote:
>
> 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]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list