stephr
stephr

Reputation: 113

Rstudio-trying to create a loop to loop through a list of column names and then change the variables to be factors. I hope to keep the pipe

I am trying to get it to work on a small data frame. So that I can then use it on a large data frame. This is my code:

df<-data.frame(x1=c(3,5,7,1),
              y1=c(4,2,9,1),
              z1=c(3,1,6,8))

for(i in colnames(df)) {
  df<-df %>% 
      mutate(i=as.factor(i))}

But it produces a data frame that looks like this:

'data.frame':   4 obs. of  4 variables:
 $ x1: num  3 5 7 1
 $ y1: num  4 2 9 1
 $ z1: num  3 1 6 8
 $ i : Factor w/ 1 level "x1": 1 1 1 1

I also tried:

for(i in colnames(df)) {
  df<-df %>% 
    factor(i)}

which produces this:

 Factor w/ 1 level "z1": NA NA NA
 - attr(*, "names")= chr [1:3] "x1" "y1" "z1"

Upvotes: 2

Views: 113

Answers (1)

akrun
akrun

Reputation: 887571

We can use := with !! instead of =asi` is not evaluated

for(i in colnames(df)) {
  df<-df %>% 
      mutate(!!i:=as.factor(!!rlang::sym(i)))
}

-output

> str(df)
'data.frame':   4 obs. of  3 variables:
 $ x1: Factor w/ 4 levels "1","3","5","7": 2 3 4 1
 $ y1: Factor w/ 4 levels "1","2","4","9": 3 2 4 1
 $ z1: Factor w/ 4 levels "1","3","6","8": 2 1 3 4

But, this is more easier in tidyverse, using across

df <- df %>%
       mutate(across(everything(), factor)

Upvotes: 1

Related Questions