sbac
sbac

Reputation: 2081

How to use arguments of to_factor in tidyverse

I am trying to convert variables a and b into factors, but I want to use two arguments of to_factor namely drop_unused_labels and ordered. But I receive an error when I try to use them in the context of mutate_at. Is there an alternative syntax to use it?

library(tidyverse)
library(labelled)
df <- data.frame(
  a = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2)),
  b = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2, DK = 3))
)

# converting vars a and b to factor

glimpse(df %>% mutate_at(vars(a:b), to_factor))
#> Rows: 4
#> Columns: 2
#> $ a <fct> No, No, Yes, 3
#> $ b <fct> No, No, Yes, DK

# But I want to use two arguments of to_factor
glimpse(df %>% mutate_at(vars(a:b), 
                          to_factor(drop_unused_labels=TRUE, ordered=TRUE)))
#> Error in var_label(x): argument "x" is missing, with no default

Created on 2020-09-29 by the reprex package (v0.3.0)

Upvotes: 1

Views: 152

Answers (2)

akrun
akrun

Reputation: 887501

Using mutate with across

library(dplyr)
df %>%
    mutate(across(a:b, ~ to_factor(.x, drop_unused_labels = TRUE, ordered = TRUE)))

Upvotes: 1

Paul
Paul

Reputation: 9107

Parameters can be passed as arguments after the function.

df %>%
  mutate_at(
    vars(a:b), 
    to_factor,
    drop_unused_labels = TRUE,
    ordered = TRUE
  )

Alternatively, you can specify the function

df %>%
  mutate_at(
    vars(a:b), 
    function(x) to_factor(x, drop_unused_labels = TRUE, ordered = TRUE)
  )

Or equivalently

df %>%
  mutate_at(
    vars(a:b), 
    ~to_factor(., drop_unused_labels = TRUE, ordered = TRUE)
  )

Upvotes: 2

Related Questions