开发者

creating a new variable according to existing variables using R

开发者 https://www.devze.com 2023-02-22 03:28 出处:网络
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 bel开发者_C百科ow:

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 bel开发者_C百科ow:

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)


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

精彩评论

暂无评论...
验证码 换一张
取 消