rfor-loop

Automatize as.factor function on some variables via a for loop


I was struggling with the iteration of as.factor() function on the following list of variables.

d$var1 <- as.factor(d$var1)
d$var2 <- as.factor(d$var2)
d$var3 <- as.factor(d$var3)
d$resp_correct <- as.factor(d$resp_correct)
d$second_response <- as.factor(d$second_response)

I was wondering how to create some code lines with either a for loop to iterate the as.factor function on such a list. Actually I used the following code

d %>% 
  dplyr::select(
    var1, var2, var3, resp_correct, second_response) %>% 
  lapply(., as.factor) %>% 
  lapply(., is.factor)

But when going to verify variable singularly, that doesn't seem to work.

> is.factor(d$var1)
[1] FALSE

Which one could be the problem? How it would be possible to code a good for loop? Thanks for replying


Solution

  • You could use dplyr's across function:

    library(dplyr)
    
    d <- d %>%
      mutate(across(c(block, CR, T1.ACC, T1.correct, T1.response), as.factor))
    

    If you really want to use a for-loop, you could use

    for (i in c("block", "CR", "T1.ACC", "T1.correct", "T1.response")){
      
      d[, i] <- as.factor(d[, i])
    }