Using across to convert column types

How would you use across to convert many columns to factor. For example using the starwars dataset:

library(dplyr)

starwars %>% 
  select(height, hair_color, skin_color, mass)

# A tibble: 87 x 4
   height hair_color    skin_color   mass
    <int> <chr>         <chr>       <dbl>
 1    172 blond         fair           77
 2    167 NA            gold           75
 3     96 NA            white, blue    32
 4    202 none          white         136
 5    150 brown         light          49
 6    178 brown, grey   light         120
 7    165 brown         light          75
 8     97 NA            white, red     32
 9    183 black         light          84
10    182 auburn, white fair           77
# ... with 77 more rows

starwars %>% 
  select(height, hair_color, skin_color, mass) %>% 
  mutate(across(height:skin_color), as.factor()) # fix this !!!

Error: Problem with `mutate()` input `..2`.
x argument "x" is missing, with no default
i Input `..2` is `as.factor()`.

Try the following code. Notice that as.factor is inside of across() and is used without parentheses.

starwars %>% 
  select(height, hair_color, skin_color, mass) %>% 
  mutate(across(height:skin_color, as.factor))
2 Likes

Thanks for the explanation.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.