I am trying to coerce numeric columns in a data frame to factors. The coercion works OK except that instead of the labels I specify I get a numeric label for each row of the data frame. There are no error messages.
I've tried tidyverse and base approaches; coerced the target vector to character (and even to integer) before coercing to factor; run the same code over a tibble rather than a data frame just in case it was to do with the row names. And I have searched here and other R-related parts of the internet.
I feel sure I am missing something obvious here, but as happens when one looks at a problem for too long, I just can't see it.
df <- data.frame("a" = c(1, 2, 2), "b" = c(2, 1, 1), row.names = NULL, stringsAsFactors = FALSE)
df$a <- factor(df$a, levels = c("1", "2"), labels = c("yes", "no"))
# coercion to factor worked:
class(df$a)
#> [1] "factor"
typeof(df$a)
#> [1] "integer"
levels(df$a)
#> [1] "yes" "no"
labels(df$a) # same as no. rows in df. Add rows and more labels appear.
#> [1] "1" "2" "3"
df$a
#> [1] yes no no
#> Levels: yes no
Created on 2020-09-24 by the reprex package (v0.3.0)