Home > database >  Replacing dots with underscores, when using make.names or renaming obejcts in the working environmen
Replacing dots with underscores, when using make.names or renaming obejcts in the working environmen

Time:04-11

I am using this (ill advised, I know) solution to automatically name Excel files when uploading a folder.

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)

Now, make.names uses . to make correct names, while I would rather use _. What would be the best way to dynamically change the dots to underscores?

I tried to do something like lapply(ls(),gsub(".", "_")), but that does not seem to work. I would also prefer to do it within list2env, but I'll settle for a separate line.

CodePudding user response:

The issue is probably that use you use "." which in a regex matches every character. If you want to match a . in a string you have to escape it using use "\\.".

Personally I don't like it to wrangle all code in one line when you could use a simple function to make the code cleaner and more understandable.

# Example data
write.csv(mtcars, "mt cars.csv")
write.csv(mtcars, "mt car s.csv")

temp = list.files(pattern="*.csv")

make_names <- function(x) {
  gsub("\\.", "_", make.names(gsub("*.csv$", "", x)))
}
names(temp) <- make_names(temp)

list2env(lapply(temp, read.csv), envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

ls()
#> [1] "make_names" "mt_car_s"   "mt_cars"    "temp"
  • Related