Skip to content

Converting code to R Question

4 messages · Craig J, Jeremy Miles, William Dunlap +1 more

#
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:
#
Note that in
  Variable <- 0 + (item1 == 1) + (item2 == 1) + (item3 == 1) + (item4 == 1)
the '0 +' is not needed, since adding logicals produces integers.

Your second solution
   Variable <- sum((item1 == 1), (item2 == 1) , (item3 == 1) , (item4 == 1), na.rm=TRUE)
gives the wrong answer, since sum() always returns a scalar.  You could treat logical
NA's as FALSE's by defining
   is.true <- function(x) !is.na(x) & x
and using it as
   Variable <- is.true(item1==1) + is.true(item2==1) + is.true(item3==1) + is.true(item4==1)


Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
If you do this sort of thing a lot you may find the psych package helpful:

# make example data
x <- 1:3
dat <- data.frame(expand.grid(Item1=x, Item2=x, Item3=x, Item4=x))

# make scoring ky
key <- c(Item1=1, Item2=2, Item3=1, Item4=1)

# load psych library
library(psych)

# score
(scores <- score.multiple.choice(key, dat, total=TRUE, short=FALSE))
dat$Variable <- scores$scores

Best,
Ista
On Mon, Feb 25, 2013 at 8:02 PM, Craig J <cjohns38 at gmail.com> wrote: