Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

R: Generate dynamic names for dataframes

I need to read several csv files from a directory and save each data in separate dataframe. The filenames are in a character vector:

lcl_forecast_data_files <- dir(lcl_forecast_data_path, pattern=glob2rx("*.csv"), full.names=TRUE)

For example: "fruc2021.csv", "gem2020.csv", "strb2021.csv".

So far I am reading the files step by step:

fruc2021 <- read_csv2("fruc2021.csv")
gem2020 <- read_csv2("gem2020.csv")
strb2010 <- read_csv2("strb2021.csv")

But there are many more files in the directory and subdirectories. To read them all one by one is very tedious.

Now I have already experimented a little with the map function, but I have not yet figured out how to automatically generate the names of the dataframes from the file names.

A first simple try was:

lcl_forecast_data <- lcl_forecast_data_files %>% 
  map(
    function(x) {
      str_replace(basename(x), ".csv","") <- read_csv2(x)
    }
  )

But this did not work :-(

Is it even possible to generate names for dataframes like this? Or are there other, simpler possibilities?

Greetings Benne

Translated with www.DeepL.com/Translator (free version)

question from:https://stackoverflow.com/questions/65883022/r-generate-dynamic-names-for-dataframes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you do not want to use a list and lapply as @Onyambu suggested you can use assign() to generate the dataframes.

filenames <- c("fruc2021.csv", "gem2020.csv", "strb2021.csv")

for (i in filenames) {
    assign(paste('',gsub(".csv","",i),sep=''),read.csv(i))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...