Skip to content
Prev 318310 / 398503 Next

Converting code to R Question

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