Suppose we have the following data.table:
x_dt <- data.table(sexn = c(1, 0, 0, 1, NA, 1, NA),
country = c("CHN", "JPN", "BGR", "AUT", " ", "TWN", " "),
age = c(35, NA, 40, NA, 70, 18, 36)
)
I am trying to create a variable asia_region, which has a value of 1 when country %chin% c("CHN", "JPN", "KOR", "SGP", "TWN"), a value of 0 when country is not missing and NA when country is missing.
The following code populates 0's when country is missing.
result <- x_dt[, asia_region := ifelse(country %chin% c("CHN", "JPN", "KOR", "SGP", "TWN"),1 , 0)]