简体   繁体   中英

How to recode data using dplyr::recode when variables have a space

I have

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

However if my data have spaces in them this method does not work

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")

Is there anything I can do to fix this other than changing the data?

If your categories have a space or... you have to wrap them in quotes or backticks:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM