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$block <- as.factor(d$block)
d$CR <- as.factor(d$CR)
d$T1.ACC <- as.factor(d$T1.ACC)
d$T1.correct <- as.factor(d$T1.correct)
d$T1.response <- as.factor(d$T1.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(
    block, CR, T1.ACC, T1.correct, T1.response) %>% 
  lapply(., as.factor) %>% 
  lapply(., is.factor)

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

> is.factor(d$block)
[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])
    }