Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with str_replace in many columns and for

I'm a noob in R.

I'm working with a dataframe of like 150 rows and 21 columns. I want to change from column 5 to 20 the character "-" to "0.00".

I'm using this code and it works individually:

datos$max52sem<-str_replace(datos$max52sem,"-","0.00")
datos$min52sem<-str_replace(datos$min52sem,"-","0.00")

I'm trying to use a "for" to change it from all columns, instead of writing all my variables' names 15 times.

This is what I'm writing:

mis_vars<-c("max52sem","min52sem","cierre_prev","cierre_hoy","max_hoy","min_hoy","ret_hoy","ret_sem","ret_mes","ret_año","ret_ytd","vol","upa","vla","pvla","pu")
for(x in mis_vars)
  datos$x<-str_replace(datos$x,"-","0")

"mis_vars" are the names of my columns (variables) I want to change in my dataframe, but I get this answer from R and I don't know what I'm doing wrong.

Error in $<-.data.frame(*tmp*, "x", value = character(0)) : replacement has 0 rows, data has 1220>

like image 331
Ivette Tejeda Avatar asked Oct 12 '25 01:10

Ivette Tejeda


2 Answers

With dplyr, we can use mutate_at

library(dplyr)
library(stringr)
datos <- datos %>%
             mutate_at(vars(mis_vars), ~ str_replace(., "-", "0"))

In the OP's for loop, instead of datos$x <-, it should be datos[[x]] <- as it will be creating a column named 'x' instead of the variable in 'mis_vars'


Or using only base R

datos[mis_vars] <- lapply(datos[mis_vars], sub, pattern = "-", replacement = "0")
like image 176
akrun Avatar answered Oct 14 '25 18:10

akrun


In base R, we can use lapply to change multiple columns

datos[mis_vars]  <- lapply(datos[mis_vars], function(x) sub("-", "0.00", x))
like image 36
Ronak Shah Avatar answered Oct 14 '25 17:10

Ronak Shah