用plyr :: revalue替换空值

时间:2018-02-23 10:49:58

标签: r dplyr plyr

我有一个向量,我想根据另一个向量替换一些值。

我使用plyr::revalue

x = c("a", "b", "c", "d", "", "  ", "d, ", "aaaaa")
var.replace = c("d"=NA, "a"="A")
x %>%  plyr::revalue(var.replace)
#[1] "A"      "b"      "c"      NA       ""       "  "     "d, "    "aaaaa"
var.replace = c("d"=NA, "a"="A", ""=NA)
#Error: attempt to use zero-length variable name

我知道问题One of the factor's levels is an empty string; how to replace it with non-missing value?中有一个接受的答案,但我正在寻找一种优雅的单行,以整齐的精神。

是否存在?

2 个答案:

答案 0 :(得分:3)

Akrun回答让我明白了!碰巧你只需要省略名称为空的密钥:

> setNames(c(NA, "A", NA), c("d", "a", ""))
#  d   a     
# NA "A"  NA 
> c("d"=NA, "a"="A", NA)
#  d   a     
# NA "A"  NA

然后,公式变得非常简单:

var.replace = c("d"=NA, "a"="A", NA)
x %>%  revalue(var.replace)

答案 1 :(得分:2)

我们可以使用setNames创建""作为名称,然后执行revalue

var.replace <- setNames(c(NA, "A", NA), c("d", "a", ""))
x %>%
    plyr::revalue(var.replace)
#[1] "A"     "b"     "c"     NA      NA      "  "    "d, "   "aaaaa"