如何将读取的数据帧保存为R中的列表?

时间:2022-12-14 00:28:19

I have say about 10 .txt files in my directory that I read like this:

我在我的目录中说了10个.txt文件,我这样读了:

sampleFiles <- list.files(directory)
for (i in 1:length(sampleFiles)) {
 table <- read.table( sampleFiles[i], header = TRUE)
}

I want to store the read file such that I can access them as table1 for i=1, table2 for i=2 and tablen for i=n. How can I read all these files and save as dataframe base names table?

我想存储读取文件,以便我可以将它们作为table1访问i = 1,table2 for i = 2和tablen for i = n。如何读取所有这些文件并保存为数据框基本名称表?

2 个解决方案

#1


2  

Use lapply

Data <- lapply( list.files(directory), read.table, header=TRUE)

In order to access each data.frame you can use [[ as in Data[[1]], Data[[2]],...,Data[[n]]

为了访问每个data.frame,你可以使用[[在数据[[1]],数据[[2]],...,数据[[n]]

Read about how to Extract or Replace Parts of an Object using [[

阅读有关如何使用[[提取或替换对象的部分]的信息[

#2


0  

To name them as you describe, replace the table <- assignment in your loop with

要在描述时命名它们,请将循环中的表< - 赋值替换为

assign(paste0("table", j), read.table(sampleFiles[j], header = TRUE))

Your question title is slightly misleading, as this is not saving the tables as a list in the formal R sense of a list (for which, see the other answer).

你的问题标题有点误导,因为这不是将表保存为正式R列表中的列表(为此,请参阅其他答案)。

#1


2  

Use lapply

Data <- lapply( list.files(directory), read.table, header=TRUE)

In order to access each data.frame you can use [[ as in Data[[1]], Data[[2]],...,Data[[n]]

为了访问每个data.frame,你可以使用[[在数据[[1]],数据[[2]],...,数据[[n]]

Read about how to Extract or Replace Parts of an Object using [[

阅读有关如何使用[[提取或替换对象的部分]的信息[

#2


0  

To name them as you describe, replace the table <- assignment in your loop with

要在描述时命名它们,请将循环中的表< - 赋值替换为

assign(paste0("table", j), read.table(sampleFiles[j], header = TRUE))

Your question title is slightly misleading, as this is not saving the tables as a list in the formal R sense of a list (for which, see the other answer).

你的问题标题有点误导,因为这不是将表保存为正式R列表中的列表(为此,请参阅其他答案)。