'Unable to create a for loop to convert multiple varialbe into as.factor
I am trying to write a for loop in r to convert multiple variables with similar character pattern in r to as.factor.
Below is the function I wrote, R runs the code, does not show any error, but does not give the desired output. There is a logical error, can someone help me correct this error?
for (i in grep(pattern = "hml35_", x=tanre)) 
{
    tanre$i<-as.factor(tanre$i)
}
Solution 1:[1]
A solution with tidyverse
library(tidyverse)
tanre %>%
  mutate_at(vars(contains("hml35_")), as.factor)
Solution 2:[2]
Assuming the grep pattern returns the column names, you need to change the syntax:
for (i in grep(pattern = "hml35_", x=tanre)) 
{
    tanre[[i]]<-as.factor(tanre[[i]])
}
R is expecting the literal column name when you use the $ operator.
Edit: You could use lapply here instead of a loop. I would also have a look at using mutate across.
Edit 2:
As requested, here is how you could do it with lapply:
# Create some data
tanre  <- data.frame(
    id = c(1:12),
    hml35_a  = rep(c("a", "b", "c"), 4),
    hml35_b = rep(c("a", "b", "c"), 4)
)
sapply(tanre, class)
#          id     hml35_a     hml35_b
#   "integer" "character" "character" 
# Make factor
tanre[grep("hml35_", names(tanre))]  <- lapply(tanre[grep("hml35_", names(tanre))], as.factor)
sapply(tanre, class)
#        id   hml35_a   hml35_b
# "integer"  "factor"  "factor"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | dvera | 
| Solution 2 | 
