[R] Odp: Better way than an ifelse statement?

Petr PIKAL petr.pikal at precheza.cz
Thu Jan 14 08:31:01 CET 2010


Hi

r-help-bounces at r-project.org napsal dne 14.01.2010 08:05:14:

> Hello All,
> 
> I am trying to create a column of weights based off of factor levels
> from another column.  I am using the weights to calculate L scores.
> Here is an example where the first column are scores, the second is my
> "factor" and the third I want to be a column of weights.  I can do
> what I want with an ifelse statement (see below), but I am wondering
> if anyone knows of a cleaner way to do this?
> 
> example <- data.frame(cbind(rnorm(4), rep(1:4, 1), c(0)))
> 
> example$X3 <- ifelse(example$X2==1, -3, (
> ifelse(example$X2==2, -1, (
> ifelse(example$X2==3, 1, (
> ifelse(example$X2==4, 3, NA))))))) ## this seems sloppy to me
> 
> > example
>            X1 X2 X3
> 1  1.75308880  1 -3
> 2 -0.49273616  2 -1
> 3 -0.12446648  3  1
> 4 -0.06417217  4  3

One way is with factor

as.numeric(as.character(factor(example$X2, labels=c(-3, -1,1,3))))

Regards
Petr


> 
> 
> Thanks for your help,
> 
> Joshua
> 
> -- 
> Joshua Wiley
> Senior in Psychology
> University of California, Riverside
> http://www.joshuawiley.com/
> 
> ______________________________________________
> 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