2

I am trying to code a new variable based on the values of three other variables. Specifically, if all of the variables are NA, I would like the new variable to take NA and if any of them are 1, it should take a 1, otherwise it should take a 0. However, I encounter an error using the following code:

frame <- data.frame(x = c(NA,NA,1), x2 = c(NA, NA, 0), x3 = c(NA,0,0))
frame

y <- ifelse(is.na(frame$x) == TRUE & is.na(frame$x2) == TRUE & is.na(frame$x3) == TRUE, NA, 0)
y2 <- ifelse(frame$x == 1 | frame$x2 == 1 | frame$x3 == 1, 1, y)

The second digit for y is correctly 0 but becomes NA when referenced in y2. Any idea on why this happens?

coding_heart
  • 1,245
  • 3
  • 25
  • 46
  • First off, `is.na(x) == TRUE` is equivalent to just `is.na(x)`. Both are logical values, so there's no need for the `== TRUE` part. – cbare May 07 '15 at 18:29

3 Answers3

5

One option to get expected output is

  do.call(pmax, c(frame, na.rm=TRUE))
  #[1] NA  0  1
akrun
  • 874,273
  • 37
  • 540
  • 662
4

You have three different conditions, so it's most natural to express it in three lines:

z <- rep(0,nrow(frame))

z[apply(is.na(frame),1,all)] <- NA
z[apply(frame==1    ,1,any)] <- 1
# [1] NA  0  1
Frank
  • 66,179
  • 8
  • 96
  • 180
  • The OP is vague as to the connection between the code and the three conditions outlined in the paragraph for the "new variable". This corresponds to the description; I don't know what to make of the code. – Frank May 07 '15 at 18:15
1

If you have a data.frame like so:

frame <- data.frame(a=letters[1:5], x1=c(1,1,NA,NA,0), x2=c(1,0,NA,0,0), x3=c(0,1,NA,1,0))

> frame
  a x1 x2 x3
1 a  1  1  0
2 b  1  0  1
3 c NA NA  NA
4 d NA  0  1
5 e  0  0  0

Something like this may do what you're after:

frame$summary <- apply(frame[,c('x1','x2','x3')], 1, function(row) {
    if (all(is.na(row))) {
        return(NA)
    } else if (1 %in% row) {
        return(1)
    } else {
      return(0)
    }})

> frame
  a x1 x2 x3 summary
1 a  1  1  0       1
2 b  1  0  1       1
3 c NA NA NA      NA
4 d NA  0  1       1
5 e  0  0  0       0

...and is a fairly direct translation of your verbal description into code.

cbare
  • 12,060
  • 8
  • 56
  • 63