0

I'm trying recode some variables using

ppar$denr <- recode(ppar$q3c, 0 =c("1"), 1 =c("2"), 2 =c("5"), 3 = c("4", "11"), 4 = c("3","6", "7", "10", "12", "77"))

It return this error

Error: unexpected '=' in "ppar$denr <- recode(ppar$q3c, 0 ="

I try use <- but return

 invalid (do_set) left-hand side to assignment
alistaire
  • 42,459
  • 4
  • 77
  • 117
Mariane Campos
  • 121
  • 1
  • 7

2 Answers2

0

In R syntax, names that start with numbers are non-syntactic and must be quoted:

dplyr::recode(factor(1:5), "1" = "A")
#> [1] A 2 3 4 5
#> Levels: A 2 3 4 5

In terms of the data, 1 is a value, not a name, but as the function recode is structured, it's used as a name.

Side note: Making factors of numbers is not a good idea, as factors are integers internally, so factors of numbers cause confusion whether operations are happening on the levels or the underlying integers.

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • Do you recommend that I change to factor after the recode ? – Mariane Campos Jul 22 '18 at 22:52
  • No; I though that's what you already had. If it's a character vector, that's less bad, but you should still convert to numeric/integer at some point. Better, start there. – alistaire Jul 22 '18 at 23:41
  • So, the variable is double but when I trying convert to factor, return this error `Error in `$<-.data.frame`(`*tmp*`, abor, value = integer(0)) : ` – Mariane Campos Jul 23 '18 at 00:24
  • Don't convert numbers to factors; see the note in the answer. But there's something wrong with your call; does it work without assignment? – alistaire Jul 23 '18 at 00:51
0

You can also do it by memisc package:

memisc::recode(ppar$q3c,
         0 <- 1,
         1 <- 2,
         2 <- 5,
         3 <- c(4, 11))

Or by car:

car::recode(ppar$q3c, "1 = 0; 2 = 1; 5 = 2; c(4, 11) = 3")
tmfmnk
  • 38,881
  • 4
  • 47
  • 67