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)
}
CodePudding user response:
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.
CodePudding user response:
A solution with tidyverse
library(tidyverse)
tanre %>%
mutate_at(vars(contains("hml35_")), as.factor)