Search code examples
rforcats

Change numeric column to factor with forcats


In my continuing quest to make sense of the tidyverse can somebody help me with this?

library(tidyverse)
foo <- tibble(x = 1:10, y = rep(1:2,5))
# why does this not work?
foo %>% as_factor(y)

I want to change foo$y from numeric to a factor. In base R I'd do foo$y <- as.factor(foo$y) and be done with it. I would think that foo %>% as_factor(y) would be the parsimonious way to do this in tidy-speak but it's not. What is the best way to accomplish it?


Solution

  • We can pull the column as a vector and apply

    library(dplyr)
    foo %>%
        pull(y) %>%
        as_factor
    

    Or make use of the tidyverse function for transformation

    foo <- foo %>%
              mutate(y = as_factor(y))