[R] ifelse help

jim holtman jholtman at gmail.com
Wed Jul 11 02:41:39 CEST 2012


Seems to work for me:

> x <- data.frame(old1 = sample(c(1,2,8), 10, TRUE), old2 = 1:10)
> x$new <- ifelse(x$old1 == 8, 1, x$old2)
> x
   old1 old2 new
1     1    1   1
2     2    2   2
3     2    3   3
4     8    4   1
5     1    5   5
6     8    6   1
7     8    7   1
8     2    8   8
9     2    9   9
10    1   10  10


On Tue, Jul 10, 2012 at 8:26 PM, Jeff <r at jp.pair.com> wrote:
>
> I'm sure this is easy, but I'm new to R and can't find any example of the
> following.
>
> Here's what I'm trying to do in pseudo-code.
>
> data$newvar <- ifelse(data$oldvar1 == 8, 1,data$oldvar2)
>
> In other words, if the existing variable equals 8, then the new variable
> should equal 1, otherwise the new variable should equal the value of another
> existing variable.
>
> I've tried to follow the examples given on the web and in the R manuals, and
> each time I get errors or unexpected values.
>
> Thanks
>
> Jeff
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list