[R] Converting code to R Question

Jeremy Miles jeremy.miles at gmail.com
Tue Feb 26 02:40:47 CET 2013


Here's a direct translation:
 Variable <- 0
 Variable <- ifelse(item1 == 1, Variable +1, Variable)
 Variable <- ifelse(item2 == 1, Variable +1, Variable)
 Variable <- ifelse(item3 == 1, Variable +1, Variable)
 Variable <- ifelse(item4 == 1, Variable +1, Variable)

Here's another way to do it:

Variable <- 0 + (item1 == 1) + (item2 == 1) + (item3 == 1) + (item4 == 1)

Note that I haven't worried about missing data - do you have NAs in
your items? If you do, and you want NA to be not equal to 1 (rather
than equal to NA):

Variable <- sum((item1 == 1), (item2 == 1) , (item3 == 1) , (item4 ==
1), na.rm=TRUE)


Jeremy


On 25 February 2013 17:02, Craig J <cjohns38 at gmail.com> wrote:
> I'm learning R and am converting some code from SPSS into R.  My background
> is in SAS/SPSS so the vectorization is new to me and I'm trying to learn
> how to NOT use loops...or use them sparingly.  I'm wondering what the
> most efficient to tackle a problem I'm working on is. Below is an example
> piece of code.  Essentially what it does is set a variable to zero, loop
> through item responses, and add one if a condition is met. For example, if
> item one was responded as a 1 then add one to the final variable.  If item
> two was responded as a 2 then add one to the final variable.  I have to do
> this for five scales with each scale having 6 items half of which may have
> the 1 response pattern and half the 2 pattern.
>
> Any suggestions on how best to tackle this in R would be helpful.
>
> Craig
>
> **********
> Old SPSS code sample
> **********
>
> Compute Variable = 0.
>
> IF (item1 = 1) Variable = Variable +1 .
>
> IF (item2= 2) Variable = Variable +1 .
>
> IF (item3 = 1) Variable = Variable +1.
>
> IF (item4 = 2) Variable = Variable +1.
>
> EXECUTE .
>
>         [[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