我如何在R中将列表中的数据框命名为它们来自的CSV文件?

huangapple go评论69阅读模式
英文:

How do I name dataframes in a list in R after the CSV file they came from?

问题

我有一个名为“Results”的文件夹,其中包含CSV文件。它们的命名方案为“Sim_Results_x.csv”,其中x是第n次模拟。我想将它们转换为一个数据框列表,这些数据框的名称与它们被读取的文件名相同。例如,我希望Sim_Results_1.csv在数据框列表中被称为Sim_Results_1,而不是[[1]]。我尝试了下面的代码,但是它并没有以文件名命名数据框,而是将第一列命名为文件名,所有其他列都被命名为“NA”。我该如何解决这个问题?
英文:

I have a folder called "Results" with CSV files in it. The naming scheme of them is "Sim_Results_x.csv", where x is the nth simulation. I want to make these into a list of dataframes which are named after the file they were read in from. So for example, I want Sim_Results_1.csv to be called Sim_Results_1 in the list of dataframes, rather than [[1]]. I tried the code below but instead of naming the dataframe after the file, it names the first column after the file, and all other columns are named "NA." How could I fix this?

#get list of names of all files in results folder
filenames <- list.files("Results", pattern="*.csv", full.names=TRUE)
#sort them in numeric order
filenames <- mixedsort(filenames)
#combine into list of dataframes
ldf <- lapply(filenames, function(x) {
  name <- tools::file_path_sans_ext(basename(x))
  df <- read.csv(x)
  names(df) <- name
  # Return dataframe
  df
})

答案1

得分: 0

你可以使用基本的R setNames() 函数。关键是你要将名称应用于列表,而不是列表中的每个项目。

ldf <- lapply(filenames, read.csv) |>
    setNames(
        tools::file_path_sans_ext(basename(filenames))
    )
英文:

You can use the base R setNames() function. The key point is that you are applying the names to the list, rather than to each item in the list.

ldf &lt;- lapply(filenames, read.csv) |&gt;
    setNames(
        tools::file_path_sans_ext(basename(filenames))
    )

答案2

得分: 0

使用Map/read.csv,然后按照最后一行所示编辑列表名称。

library(tools)
ldf <- Map(read.csv, filenames)
names(ldf) <- file_path_sans_ext(basename(names(ldf)))
英文:

Use Map/read.csv and then edit the lists names as shown in the last line.

library(tools)
ldf &lt;- Map(read.csv, filenames)
names(ldf) &lt;- file_path_sans_ext(basename(names(ldf))

huangapple
  • 本文由 发表于 2023年4月11日 01:15:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定