用一些空字符串重新编码字符向量 [英] Recode character vector with some empty strings

查看:50
本文介绍了用一些空字符串重新编码字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 dplyr :: recode()函数重新编码一些变量。我有一个带有一些空字符串的字符变量,我也想重新编码。但是,如果我在函数的参数中引用空字符串,则会出现错误。

I have been using the dplyr::recode() function to recode some variables. I have one character variable with some empty strings that I would also like to recode. But if I refer to the empty string in the arguments to the function, I get an error.

# input
x <- c("a", "b", "", "x", "y", "z")
# desired output
c("Apple", "Banana", "Missing", "x", "y", "z")

dplyr::recode(x, "a"="Apple", "b"="Banana", ""="Missing")

Error: attempt to use zero-length variable name

如果我将空字符串视为缺失值,该函数将其保留为空字符串。

If I treat the empty string as a missing value, the function leaves it as an empty string.

dplyr::recode(x, "a"="Apple", "b"="Banana", .missing="Missing")

[1] "Apple"  "Banana" ""       "x"      "y"      "z"     

如何重新编码值以获得所需的输出?

How can I recode the values to get the desired output?

推荐答案

您可以使用 na_if 来获取 .missing 工作正常:

You can use na_if to get .missing working properly:

x <- c("a", "b", "", "x", "y", "z")
dplyr::recode(na_if(x,""), "a"="Apple", "b"="Banana", .missing="Missing")

[1] "Apple"   "Banana"  "Missing" "x"       "y"       "z" 

这篇关于用一些空字符串重新编码字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆