如何在R语言的列表中将字符(0)转换为NA?

时间:2017-06-26 18:30:49

标签: r list

如何使用R语言将character(0)转换为NA

示例:

a = list("a", "character(0)", "b", "c")

a = list("a", "NA", "b", "c")

感谢。

2 个答案:

答案 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"

鉴于你的例子,这提供了你所要求的,但实际上你想要的是什么?