我想把包含name的赋值为1,把缺失的赋值为0。我试着用它,但不能让它运行。谢谢你的帮助。
Individual <- c("Jeff","NA","John","NA","NA")
Outcome: 1 0 1 0 0
您实际上并不需要ifelse
,因为您可以将逻辑值转换为整数。用途:
Individual <- c("Jeff","NA","John","NA","NA")
result <- as.integer(Individual != 'NA')
result
#[1] 1 0 1 0 0
但是,如果您有实际的NA
值而不是字符串"NA"
,我们可以使用is.na
来检查。
Individual <- c("Jeff",NA,"John",NA,NA)
result <- as.integer(!is.na(Individual))
result
#[1] 1 0 1 0 0
也可以使用ifelse
:
Individual <- c("Jeff","NA","John","NA","NA")
ifelse(Individual == "NA", 0L, 1L)
#> [1] 1 0 1 0 0
或者如Ronak所建议的NA
:
Individual <- c("Jeff", NA, "John", NA, NA)
ifelse(is.na(Individual), 0L, 1L)
#> [1] 1 0 1 0 0
我认为ifelse
解决方案更容易阅读。另一方面,Ronaks的解决方案要快得多(即大约快10倍)。
由reprex包(v1.0.0)创建于2021-02-07