baz
baz

Reputation: 7117

creating a new variable according to existing variables using R

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)

Upvotes: 1

Views: 5419

Answers (1)

Chase
Chase

Reputation: 69231

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))

Upvotes: 2

Related Questions