简体   繁体   中英

Creation of summary variable in R with values of “substitution” variable if focal variable is NA

I have a question. I have three "Nationality" variables in my dataset (as three separate columns):

  1. "Nationality_birth",
  2. "Nationality_now"
  3. "Nationality_difference" (this variable has a value, if "Nationality_birth" and "Nationality_now" are diverging - indicating which of the two nationalities someone feels more detached to -, otherwise NA)

Now I want to create a fourth variable "Nationality", which is based on "Nationality_difference" (focal variable), but has the values of "Nationality_birth" (substitute variable) if "Nationality_difference" is NA.

I tried the following code:

data$Nationality <- data$Nationality_difference
data$Nationality[is.na(data$Nationality_difference)] <- data$Nationality_birth

I get the following error:

Error in data$Nationality[is.na(data$Nationality_difference)] <- data$Nationality_birth : 
replacement has length zero

What am I missing?

Thanks a lot in advance!

You can try:

data$Nationality <- 
   ifelse(!is.na(data$Nationality_difference), 
            data$Nationality_difference, 
            data$Nationality_birth)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM