On Wed, 19 Jun 2013, Brian Perron <beper...@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 ______________________________________________ R-help@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.