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

Time:12-23

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?

CodePudding user response:

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"
  • Related