1

I would like to create a new variable with the values to be determined by the corresponding values of two existing variables. My data set is similar to the one below:

aid <- c(1,2,3,4,5)
temp <- c(38,39,NA,41,NA)
surv1 <- c(5,8,0,6,9)
data <- data.frame(aid,temp,surv1)

Now, I would like to create a new variable called surv2. That is, if temp is NA then surv2 should also be an NA; and if temp is not NA then surv2 should take the value of surv1

#The final data should look like this:
aid <- c(1,2,3,4,5)
temp <- c(38,39,NA,41,NA)
surv1 <- c(5,8,0,6,9)
surv2 <- c(5,8,NA,6,NA)
1
  • baz - I removed the "" around the NA's so that R correctly interpreted them as not available and not as the character string "NA". Commented Apr 6, 2011 at 4:57

1 Answer 1

2

ifelse evaluates a condition (whether or not temp is NA) in an element by element fashion. We will test whether or not temp is NA and assign the resulting value as NA or surv1 depending on the outcome.

data$surv2 <- with(data, ifelse( is.na(temp), NA, surv1))
Sign up to request clarification or add additional context in comments.

3 Comments

! Thanks alot for that. I was using this script: data$surv2 <- ifelse(is.na(data$temp,NA,data$surv1) but it did not work because it was reading "NA" as a character string. After you mention it, I removed the "" from NAs and it worked and gave the same output. The "" was not intentional but it gave me what I did not want. Anyway, thanks again!
If this answer solved your problem, don't forget to accept it as such. :)
@Roman, yes, indeed and just used it because it gave me what I wanted and am accepting it as such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.