Home > database >  How to specify function arguments within mutate_at
How to specify function arguments within mutate_at

Time:12-02

I want to convert multiple columns of a data.frame from the character class to the factor class while specifying the factor labels.

First I will create a dummy data.frame on which the code should such that others can reproduce the issue as follows:

df <- data.frame(replicate(2,sample(0:1,20,rep=TRUE)),
                 replicate(2,sample(0:2,20,rep=TRUE)))
names(df) <- c("xxx_var1", "xxx_var2", "yyy_var1", "yyy_var2")

I have managed to convert the desired columns as follows:

df <- df %>%
   mutate_at(vars(starts_with("xxx")), factor)

Now I want to specify arguments in the factor() function but I don't know how. If I try the following:

df <- df %>%
   mutate_at(vars(starts_with("xxx")), factor(labels = c("no", "yes"))

it returns the following error:

Error in factor(labels = c("no", "yes")) : invalid 'labels'; length 2 should be 1 or 0

Is it possible to specify the factor labels for all these columns at once using mutate_at?

CodePudding user response:

Provide factor's "labels" argument as a named argument to mutate_at:

df %>% 
  mutate_at(vars(starts_with("xxx")), factor, labels = c("no", "yes"))

However, the mutate_xxx functions have been superseded by the use of mutate and the new across function. As Jon Spring commented, the following is equivalent:

df %>% 
  mutate(across(starts_with("xxx"), ~factor(., levels = c("no", "yes"))))
  • Related