如何使用R语言将character(0)
转换为NA
?
示例:
a = list("a", "character(0)", "b", "c")
到
a = list("a", "NA", "b", "c")
感谢。
答案 0 :(得分:9)
仅替换character(0)
(假设您的意思是character(0)
而不是"character(0)"
):
a = list("a", character(0), "b", "c")
lapply(a, function(x) if(identical(x, character(0))) NA_character_ else x)
#[[1]]
#[1] "a"
#[[2]]
#[1] NA
#[[3]]
#[1] "b"
#[[4]]
#[1] "c"
替换所有长度为0的元素:
a[lengths(a) == 0] <- NA_character_
a
#[[1]]
#[1] "a"
#[[2]]
#[1] NA
#[[3]]
#[1] "b"
#[[4]]
#[1] "c"
答案 1 :(得分:2)
a[a=="character(0)"] <- "NA"
鉴于你的例子,这提供了你所要求的,但实际上你想要的是什么?