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?
mapfunctions frompurrrpackage? Also, can you provide a sample of the data you are using to make the problem reproducible in our machines? You can do that using dput(head(df)) and copying the result from the console.dfas plain text e.g. the output fromdput(df).df %>% mutate_at(vars(starts_with("xxx")), factor, labels = c("no", "yes"))?library(dplyr); df %>% mutate(across(starts_with("xxx"), ~factor(., levels = c("no", "yes"))))