【问题标题】:How to recode data using dplyr::recode when variables have a space当变量有空格时如何使用 dplyr::recode 重新编码数据
【发布时间】:2022-01-23 22:40:35
【问题描述】:

我有

myColors <- c("red", "purple", "blue", "blue", "orange", "red", "orange")
library(dplyr)
recode(myColors, red="rot", blue="blau", purple="violett")

但是,如果我的数据中有空格,则此方法不起作用

myColors <- c("Color red", "Color purple", "Color blue", "Color blue", "Color orange", "Color red", "Color orange")
recode(myColors, Color red="rot", Color blue="blau", Color purple="violett")

除了更改数据,我还能做些什么来解决这个问题?

【问题讨论】:

  • 用引号括起来,即"Color red"="rot"
  • 哇,我没想到这一点。请把它作为一个答案,以便我可以关闭
  • 你可以在 R 中使用反引号("``") 来表示非语法名称

标签: r dplyr recode


【解决方案1】:

如果您的类别有空格或……您必须将它们用引号或反引号括起来:

myColors <- c("Color red", "Color purple", "Color blue", "Color blue", "Color orange", "Color red", "Color orange")

dplyr::recode(myColors, "Color red" = "rot", `Color blue` = "blau", "Color purple" = "violett")
#> [1] "rot"          "violett"      "blau"         "blau"         "Color orange"
#> [6] "rot"          "Color orange"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 2019-01-08
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多