[R] Recoding variables (without recode() )

PIKAL Petr petr.pikal at precheza.cz
Fri Jan 25 11:05:29 CET 2013


Hi

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of David Studer
> Sent: Friday, January 25, 2013 9:28 AM
> To: r-help at r-project.org
> Subject: [R] Recoding variables (without recode() )
> 
> Hi everybody!
> 
> I have a rather simple question:
> 
> # play data
> persId<-c(1,2,3,1,4,5,2)
> varA<-c(11,12,13,12,14,15,10)
> df<-as.data.frame(cbind(persId, varA))
> 
> Now I'd like to create a new columns (df$new) according to the value of
> df$VarA. For  example
> df$new1 should be 1 if df$varA==2 or df$new2 should be 1 if df$varA>13.
> 
> I tried to do it like this:
> 
> if(df$varA==2) {df$new1<-1}
> 
> But, obviously, that's not how it works (I might be thinking to much in
> mySQL: update table set new1=1 where varA==2).
> 
> How can I solve this problem using "if"?

It would be quite difficult. Better to use ?ifelse or you can use the fact that TRUE is 1 and FALSE is 0 when used in calculation.

df$new <-  (df$varA==2)+0

results in df$new = 1 only if the condition is TRUE.

Regards
Petr

> I would not want to use recode() as my conditions might be more
> complicated later on.
> 
> Thank you very much!
> David
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> 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