I want to assign 1 to the one that contains name and 0 to the missing one.I tried to use ifelse, but can not get it running. Thanks for your help.

Individual <- c("Jeff","NA","John","NA","NA")Outcome: 1 0 1 0 0
2

Best Answer


You don't really need ifelse since you can convert logical values to integers. Use :

Individual <- c("Jeff","NA","John","NA","NA")result <- as.integer(Individual != 'NA')result#[1] 1 0 1 0 0

However, if you have actual NA values and not string "NA" we can use is.na to check.

Individual <- c("Jeff",NA,"John",NA,NA)result <- as.integer(!is.na(Individual))result#[1] 1 0 1 0 0

It can also be done with ifelse:

Individual <- c("Jeff","NA","John","NA","NA")ifelse(Individual == "NA", 0L, 1L)#> [1] 1 0 1 0 0

Or as suggested by Ronak with NA:

Individual <- c("Jeff", NA, "John", NA, NA)ifelse(is.na(Individual), 0L, 1L)#> [1] 1 0 1 0 0

I consider the ifelse solution to be easier to read. On the other hand, Ronaks solution is a lot faster (i.e. by about a factor 10).

Created on 2021-02-07 by the reprex package (v1.0.0)