用一些空字符串重新编码字符向量

编程入门 行业动态 更新时间:2024-10-13 00:31:15
本文介绍了用一些空字符串重新编码字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在使用 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"

更多推荐

用一些空字符串重新编码字符向量

本文发布于:2023-11-30 07:07:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   字符   空字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!