Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

I am not able to pipe the mutate() into as_factor()? I don't get an error but it just doesn't do any leveling.

I can do it one by one df$Ethnicity %<>% as_factor(), but I can not able to perform on the whole columns:

df %<>% 

     mutate(

      Gender = case_when(

      Q4 == 1 ~ "Male", 

      Q4 == 2 ~ "Female",

      TRUE ~ as.character("Other")),

      Education = case_when(

        Education_n %in% c(1:4) ~ "Low", 

        Education_n %in% c(5:8) ~ "Medium", 

        Education_n %in% c(9:11) ~ "High", 

        TRUE ~ NA_character_)) %>% 

as_factor()

1 Answer

0 votes
by (108k points)

In that case, you can simply use the across() inside the mutate() to turn a range of columns to factor.

df %<>% 

   mutate(

     Gender = case_when(

            Q4 == 1 ~ "Male", 

            Q4 == 2 ~ "Female",

            TRUE ~ as.character("Other")),

     Education = case_when(

        Education_n %in% c(1:4) ~ "Low", 

        Education_n %in% c(5:8) ~ "Medium", 

        Education_n %in% c(9:11) ~ "High", 

        TRUE ~ NA_character_)) %>%

    mutate(across(Gender:Education, as_factor))

If you are having an older version of dplyr, in that case you can use mutate_at():

mutate_at(vars(Gender:Education), as_factor)

If you want to know more about R then do check out the R programming course

Browse Categories

...