0

I am using the recode() function in the car package to recode an integer class variable in a data frame. I am trying to recode one of the values of the variable to a string that contains a single apostrophe ('). However, this does not work. I imagine it is because the single apostrophe prematurely ends assignment. So, I tried to use \' to exit the function but it doesn't work either.

I would prefer to continue using recode() but if that is not an option, alternatives are welcome.

A working example:

# Load car() and dplyr()
library(car)
library(dplyr)

# Set up df
a <- seq(1:3)
b <- rep(9,3)
df <- cbind(a,b) %>% as.data.frame(.)

# Below works because none of the recoding includes an apostrophe:
recode(df$a, "1 = 'foo'; 2 = 'bar'; 3 = 'foobar'")

# Below doesn't work due to apostrophe in foofoo's:
recode(df$a, "1 = 'foo'; 2 = 'bar'; 3 = 'foofoo's'")

# Exiting doesn't fix it:
recode(df$a, "1 = 'foo'; 2 = 'bar'; 3 = 'foofoo\'s'")
socialscientist
  • 3,759
  • 5
  • 23
  • 58

1 Answers1

0

We could escape the quotes to make it work

recode(df$a, "1 = \"foo\"; 2 = \"bar\"; 3 = \"foofoo's\"")
#[1] "foo"      "bar"      "foobar's"

A base R alternative would be to use the df$a values as numeric index to replace those values

 df$a <- c("foo", "bar", "foobar's")[df$a]
 df$a
 #[1] "foo"      "bar"      "foobar's"

Suppose if the values are not numeric and not in the sequence.

 set.seed(24)
 v1 <- sample(LETTERS[1:3], 10, replace=TRUE)
 v1
 #[1] "A" "A" "C" "B" "B" "C" "A" "C" "C" "A"
 as.vector(setNames(c("foo", "bar", "foobar's"), LETTERS[1:3])[v1])
 #[1] "foo"      "foo"      "foobar's" "bar"      "bar"      "foobar's"
 #[7] "foo"      "foobar's" "foobar's" "foo" 

Here, we replace "A" with "foo", "B" with "bar" and "C" with "foobar's". To do that, create a named key/value vector to replace values in 'v1'.

akrun
  • 874,273
  • 37
  • 540
  • 662