I have a dataframe that I have imported from an excel file, from which I select my variables of interest and introduce them in another dataframe:
datos_def <- read_excel("datos_def_excel")
datos_modelo <- subset(datos_def, select = c("SAP", "sexo", "edad","altura","peso", "niv_est","enf_cron","IMC","fuma", "sit_lab",
"frec_act_fis","estrato","ingreso","ingreso_eq","GHQ_12","m2","n_adultos","n_menores",
"ruido", "malos","agua","limpieza",
"cont_indus", "cont_otras","escasez_verde", "molest_animal", "delincuencia"))
All the variables in this dataframe are of type numeric and there are some that I need to be of type factor, so I try the following:
variables_factor <- c("SAP","sexo","niv_est","enf_cron","fuma","sit_lab","frec_act_fis","estrato",
"ruido", "malos","agua","limpieza",
"cont_indus", "cont_otras","escasez_verde", "molest_animal", "delincuencia")
datos_modelo[,variables_factor] <- as.factor(datos_modelo[,variables_factor])
However, it returns me the following error:
Error: Must use a vector in `[`, not an object of class matrix.
I have not been able to reproduce the error, however you cannot apply it
as.factor()
the way you are doing it, you should do it on each column / variable separately: