Mahir Bhatt
Mahir Bhatt

Reputation: 19

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)
}

Upvotes: 0

Views: 65

Answers (2)

SamR
SamR

Reputation: 20444

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"

Upvotes: 1

dvera
dvera

Reputation: 336

A solution with tidyverse

library(tidyverse)

tanre %>%
  mutate_at(vars(contains("hml35_")), as.factor)

Upvotes: 1

Related Questions