[R] alternative to ifelse

Enrico Schumann es at enricoschumann.net
Wed Jun 19 20:20:40 CEST 2013


On Wed, 19 Jun 2013, Brian Perron <beperron at umich.edu> writes:

> Greetings:
>
> I am looking for a way to avoid using the ifelse function for
> constructing a new variable.  More specifically, assume I have a set
> of variables with scores ranging from 1 to 30.
>
> set.seed(12345)
> x <- c(1:30)
> x1 <- sample(x, 15, replace = TRUE)
> x2 <- sample(x, 15, replace = TRUE)
> x3 <- sample(x, 15, replace = TRUE)
> x4 <- sample(x, 15, replace = TRUE)
>
> I want to construct a dichotomous variable that tests whether any of
> the variables contains the value 1.
>
> newVar <-ifelse(x1 == 1 | x2 == 1 | x3 == 1 | x4 == 1, 1, 0)
>
> I want to avoid the ifelse function because I have a number of large
> variable lists that will require new variables to be created.  I'm
> sure there is a simple way to do this, but I haven't had any luck with
> my search!
>
> Thanks in advance.
>
> Brian
>

Hi Brian,

put all your x into a matrix and use apply:

  X <- cbind(x1, x2, x3, x4)
  apply(X, 1, function(x) if (any(x == 1L)) 1 else 0)

  ## [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0

or, since TRUE and FALSE evaluate to 1 and 0 when coerced to numeric:

  as.integer(apply(X, 1, function(x) any(x == 1L)))

  ## [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0



Regards,
        Enrico       

-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list