Metaprogramming multiple columns (column names saved as a vector strings) into factors

Here is the data to start with:

library(tidyverse)

df = read_csv('https://github.com/andrew-couch/Tidy-Tuesday/raw/master/Season%202/Data/example_retail_sales.csv', show_col_types = FALSE)

print(df)
#> # A tibble: 293 × 2
#>    ds             y
#>    <chr>      <dbl>
#>  1 1/1/1992  146376
#>  2 2/1/1992  147079
#>  3 3/1/1992  159336
#>  4 4/1/1992  163669
#>  5 5/1/1992  170068
#>  6 6/1/1992  168663
#>  7 7/1/1992  169890
#>  8 8/1/1992  170364
#>  9 9/1/1992  164617
#> 10 10/1/1992 173655
#> # … with 283 more rows

dff = df |>
  mutate(yearr = year(ds),
         monthh = month(ds),
         dayy = day(ds),
         quarterr = quarter(ds),
         semesterr = semester(ds),
         ydayy = yday(ds)) |>
  select(-ds)

Then I have a vector of strings:

columns_to_factor = c('yearr', 'monthh')
one_example_column = 'yearr'

Here is my problem:

# THIS WORKS
dff |>
  mutate(factor_yearr = as.factor(!!sym(one_example_column)))

But I'm unsure how I can do the same for columns_to_factor since it has multiple entities. Just wondering if for loop is the only answer.


ex_df <- data.frame(a=letters,
                    b=LETTERS)

columns_to_factor = c('a', 'b')
one_example_column = 'a'

library(tidyverse)

ex_df %>% 
  mutate(factor_a = 
           as.factor(!!sym(one_example_column)))
ex_df %>% 
  mutate(across(.cols = all_of(columns_to_factor),
                .fns = as.factor,
                .names = "factor_{.col}"))
1 Like

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.