Rstudyer
Rstudyer

Reputation: 477

How to use loop function to rename multiple files' name after read them in R?

I have multiple files under the folder of "rawdata", after read them and assigned them as seperated dataset, i also want to rename them from "dataset 1 a.csv" to "dataset1".

I wrote the code that achieve the first goal,using the first loop read all files as a list, then use the second loop to unset the list: ldf. But I don't know where I should add the code to let R change all file's name at once? I tried to add str_replace_all (names(ldf)," ", "-") at different places, but all returned wrong outputs, and it cannot solve the issue of getting rid of ".csv". Thanks a lot~~

Here is my code:

datanames<-list.files(here("rawdata"))

ldf<-list()

for (i in (datanames)){
  ldf[[i]]<-import(here("rawdata",i))
    for (j in names(ldf)){
      assign(j,ldf[[j]], .GlobalEnv)
    }
}

Upvotes: 1

Views: 508

Answers (1)

Brian Syzdek
Brian Syzdek

Reputation: 948

I'm not sure the pattern of the name you want to replace, but if it is blank-number-blank-letter.csv, use gsub to remove. You then appear to want to add the index to the name, so paste0 with index i.

I'm not sure how you will import,but can use read.csv

Assign will assign the name.

lapply(1:length(list.files()), function(i) assign(paste0(gsub(" [0-9] [a-z].csv", "", list.files()[i]),i), read.csv(list.files()[i])))

Upvotes: 1

Related Questions