0

I am merging data frames, one of which has labelled data. However, when the data frames merge the labelled vectors become numeric. How could I keep this from happening?

The following example shows the problem with mtcars:

library(haven)
library(dplyr)
df <- data.frame(am = c(0, 1),
                 var = c("X", "Y"))

mtcars$cyl <- labelled(mtcars$cyl, c("A" = 4, "B" = 6, "C" = 8))

class(mtcars$cyl)

Here, the mtcats$cyl is "labelled".

mtcars <- merge(mtcars, df, by.x = "am", by.y = "am", all.x = TRUE)
#OR
mtcars <- left_join(mtcars, df, by = c("am"="am"))

class(mtcars$cyl)

Then mtcars$cyl becomes "numeric". I have also noticed that the same thing happens if you crop out a part of the vector, such as here:

x <- mtcars$cyl[2:6]
class(mtcars$cyl)

Here x is "numeric" too.

R-addict
  • 7
  • 5
Marco Pastor Mayo
  • 803
  • 11
  • 25
  • I can't reproduce the isssue `left_join(mtcars, df, by = c("am"="am"))$cyl %>% class [1] "haven_labelled"; > class(mtcars$cyl) [1] "haven_labelled"` assuming `labelled` is from `library(labelled)` – akrun Nov 12 '19 at 21:30
  • It turns out that once i uninstalled the package "lmerTest" the probalem went away. Interestingly, it did not appear as "haven_labelled" as @akrun says, but still, it stays as "labelled" now for me. – Marco Pastor Mayo Nov 12 '19 at 21:32
  • May be, some function from `lmerTest` masked the other function. Not clear though – akrun Nov 12 '19 at 21:33
  • ok, I used `library(labelled)` instead of `haven`, thanks – akrun Nov 12 '19 at 21:34

0 Answers0