[R] Create variable with AND IF statement

MacQueen, Don macqueen1 at llnl.gov
Mon Jan 2 21:42:36 CET 2012


I usually do this kind of thing like this:

variable3 <- rep(1,length(variable1.fac))
variable3[ variable1.fac == 0 & variable2.num >= 1 ] <- 2
variable3[ variable1.fac == 1 & variable2.num == 0 ] <- 3
variable3[ variable1.fac == 1 & variable2.num >= 1 ] <- 4

This approach is easy to read and understand, and I would (personally)
consider it analogous to the SPSS approach. This approach does require
that the variables all have the same length -- which may be intrinsically
built in to the SPSS data structure, but is not guaranteed in R (unless
all of the variables are contained in a data frame).

The key concept is that in R, the if() function is for logical objects of
length=1, only. The ifelse() function is for logical objects of length >
1. In R terminology, we would say that ifelse() is a vectorized function,
but if() is not. The SPSS if function appears to behave in a vectorized
manner.

Although nested ifelse() functions can be used in this case, I find them
harder to read.


-Don



-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 1/2/12 1:11 AM, "Richard Kolodziej" <Richard.Kolodziej at web.de> wrote:

>Hello,
>
>I'm using SPSS at work but really would like to switch to R. Right now I'm
>trying to learn R in reproducing calculations I did with SPSS but am stuck
>with something that is quite simple and comprehensible in SPSS-Syntax:
>
>IF (variable1.fac = 0 AND variable2.num = 0) variable3=1.
>IF (variable1.fac = 0 AND variable2.num >= 1) variable3=2.
>IF (variable1.fac = 1 AND variable2.num = 0) variable3=3.
>IF (variable1.fac = 1 AND variable2.num >= 1) variable3=4.
>
>I want to create four different groups out of different conditions of two
>variables:
>  * variable1.fac is a factor coded with 0 and 1
>  * variable2.num is a numerical variable with only whole numbers
>
>My problem with R is that I can't find a way to use AND in an IF statement
>that doesn't produce an error or not intended solutions.
>
>"An Introduction to R" is really unhelpful with this problem and I
>wouldn't
>have written here, if I didn't have searched for the answer.
>
>http://tolstoy.newcastle.edu.au/R/help/05/09/12136.html was helpful in
>understanding how the IF statement is written in R but didn't answer my
>question how to add an usable AND (&, |)
>https://stat.ethz.ch/pipermail/r-help/2008-November/178808.html looked
>promising but didn't do what I had intended
>
>Thanks in advance,
>Richard
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>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