[R] alternative to ifelse

Brian Perron beperron at umich.edu
Wed Jun 19 15:24:50 CEST 2013


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.

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.


More information about the R-help mailing list