如何读取多个.xlsx并在R中生成多个数据帧?

时间:2022-09-01 22:09:04

I want to read three different files in xlsx and save them in three different dataframes called excel1, excel2 and excel3. How can I do that? I think it should be something like this:

我想在xlsx中阅读三个不同的文件,并将它们保存在三个不同的dataframes中,分别是excel1、excel2和excel3。我怎么做呢?我想应该是这样的:

files = list.files(pattern='[.]xlsx') #There are three files.

for (i in 1:files){
    "excel" + i =read.xlsx(files[i])
}

3 个解决方案

#1


2  

I suggest you to use a list instead of creating 3 variables in the current workspace:

我建议您使用一个列表,而不是在当前工作空间中创建3个变量:

dfList <- list()
for (i in 1:files){
    dfList[[paste0("excel",i)]] <- read.xlsx(files[i])
}

Then you can access to them in this way :

然后你可以用这种方式访问它们:

dfList$excel1
dfList$excel2
dfList$excel3

or :

或者:

dfList[[1]]
dfList[[2]]
dfList[[3]]

But, if you really really want to create new variables, you can use assign function :

但是,如果你真的想要创建新的变量,你可以使用赋值函数:

for (i in 1:files){
    assign(paste0("excel",i), read.xlsx(files[i]))
}
# now excel1, excel2, excel3 variables exist...

#2


2  

You can use plyr also and it's a good practice to mention the environment in which you want to create the variable:

你也可以使用plyr,这是一个很好的实践来提及你想要创建变量的环境:

library(plyr)
l_ply(1:length(files), function(i) assign(paste0('excel',i),read.xlsx(files[i]), envir=globalenv()))

#3


0  

If someone tries to use this code, this parameters are really helpful:

如果有人试图使用这段代码,这些参数非常有用:

  library(xlsx)

  files = list.files(pattern='[.]xlsx')
  dfList <- list()

  for (i in 1:length(files)){
      dfList[[paste0("excel",i)]] <- read.xlsx(files[i],header=T,stringsAsFactors=FALSE,sheetIndex = 1)
  }

#1


2  

I suggest you to use a list instead of creating 3 variables in the current workspace:

我建议您使用一个列表,而不是在当前工作空间中创建3个变量:

dfList <- list()
for (i in 1:files){
    dfList[[paste0("excel",i)]] <- read.xlsx(files[i])
}

Then you can access to them in this way :

然后你可以用这种方式访问它们:

dfList$excel1
dfList$excel2
dfList$excel3

or :

或者:

dfList[[1]]
dfList[[2]]
dfList[[3]]

But, if you really really want to create new variables, you can use assign function :

但是,如果你真的想要创建新的变量,你可以使用赋值函数:

for (i in 1:files){
    assign(paste0("excel",i), read.xlsx(files[i]))
}
# now excel1, excel2, excel3 variables exist...

#2


2  

You can use plyr also and it's a good practice to mention the environment in which you want to create the variable:

你也可以使用plyr,这是一个很好的实践来提及你想要创建变量的环境:

library(plyr)
l_ply(1:length(files), function(i) assign(paste0('excel',i),read.xlsx(files[i]), envir=globalenv()))

#3


0  

If someone tries to use this code, this parameters are really helpful:

如果有人试图使用这段代码,这些参数非常有用:

  library(xlsx)

  files = list.files(pattern='[.]xlsx')
  dfList <- list()

  for (i in 1:length(files)){
      dfList[[paste0("excel",i)]] <- read.xlsx(files[i],header=T,stringsAsFactors=FALSE,sheetIndex = 1)
  }