编写 for 循环以读取 Excel 表格

问题描述

我需要将多个工作表从 excel 读取到 R(到单独的数据帧中)。我不知道如何编写 for 循环,所以我只使用了蛮力。

这是我的代码

NSData dataOutputNumDetections

这可行,但我希望有人能告诉我如何使用 for 循环或 lapply 来代替。我还需要上传数据文件吗?我是这个网站的新手。

谢谢。

解决方法

我们可以在工作表编号索引上使用循环并将其读入 list

mylist <- lapply(1:9,function(i) read_excel("excel_data.xlsx",sheet = i))

最好将其保存在 list 中,而不是在全局环境中创建多个对象。 list 也可以命名为

names(mylist) <- paste0('mydata',seq_along(mylist))

并且可以使用[[$

提取元素
mylist[["mydata1"]]
mylist$mydata2

使用 for 循环,可以先初始化 list

mylist2 <- vector('list',9)
for(i in seq_along(mylist2)) {
    mylist2[[i]] <- read_excel("excel_data.xlsx",sheet = i)
 }
,

这个问题answers有很多out there

无论如何,对于 R 新手来说,一个简单的解决方案可能是:

# load library
library("openxlsx")

# set path to the directory containing the files
myDir <- "path/to/files/"

# read all the files in the directory
fileNames <- list.files(myDir)

# declare empty list
allFiles <- list()

# set counting index
i <- 1

# loop through the files in myDir
for (fileN in fileNames) {
    # read the file and store in position i
    allFiles[[fileN]] <- read.xlsx(paste(myDir,fileN,sep=""))
    # go to next position by updating the counting index
    i <- i + 1
}
# at this point you can access your files by,for instance:
allFiles[[1]]
# where 1 is the first file in your file list

或者,如果您不想使用计数索引:

# load library
library("openxlsx")

# set path to the directory containing the files
myDir <- "path/to/files/"

# read all the files in the directory
fileNames <- list.files(myDir)

# declare empty list
allFiles <- list()

# loop through the files in myDir
for (fileN in fileNames) {
    # read the file and store it into the list
    allFiles[[fileN]] <- read.xlsx(paste(myDir,sep=""))
}
# at this point you can access your files by,for instance:
allFiles[[fileN]]
# where fileN is the variable you just used in the for loop
# or you can access them using the actual file names but with quotes
allFiles[["actual_file_name"]]