Home > Software design >  Concatenate a string with integer in loop to convert columns to factor [duplicate]
Concatenate a string with integer in loop to convert columns to factor [duplicate]

Time:09-29

I need convert some columns of my dataset and I wish create a loop to do this instead of type line to line. But compiler show error.

Do this loop

for (i in dados_full[, 'id.'   length(12:38)]){
    dados_full = factor(dados_full[, 'id.'  i])
    i =  1
  }
Error in "id."   length(12:38) : non-numeric argument to binary operator

Instead of

dados_full[,"id.13"] = factor(dados_full[,"id.13"]) 
dados_full[,"id.14"] = factor(dados_full[,"id.14"]) 
dados_full[,"id.15"] = factor(dados_full[,"id.15"])
dados_full[,"id.16"] = factor(dados_full[,"id.16"]) 
dados_full[,"id.17"] = factor(dados_full[,"id.17"])

What to do?

CodePudding user response:

We may use lapply to loop over the columns and convert to factor

nm1 <- paste0("id.", 13:17)
dados_full[nm1] <- lapply(dados_full, factor)

Or with dplyr

library(dplyr)
dados_full <- dados_full %>%
     mutate(across(starts_with('id.'), factor))

In the OP's code, the is used for pasteing, but it wouldn't work in R. We need paste as operator overloading is not a case in R

nm1 <- paste("id.", 12:38)
for (nm in nm1){
   dados_full[[nm]] <-  factor(dados_full[[nm]])
  
 }
  • Related