使用 read_excel 从 R 中的 excel 文件中读取有限行数

Read limited number of rows from excel file in R with read_excel

我正在使用 readxl 包在 R 中读取 excel 文件,如下所示:

library(readxl)
file_names <- list.files(pattern = ".xlsx")

list_collection <- list() 
for(i in 1:length(file_names)){
  frame <- read_excel(file_names[i], )
  frame_sub <- frame[1:100,]
  list_collection[i] <- list(frame_sub)  
}

因为有很多excel个文件,我只想要前100行。显然,这是没有效率的。有没有办法一开始只从 excel 中读取 100 行,而不是读取整个文件然后进行子集化?

试试 xlsx::read.xlsx()。它具有用于指定开始行和结束行的参数。另请注意,我对您的 for() 循环做了一些改进(内存分配是最重要的)。

library(xlsx)
## get file names
file_names <- list.files(pattern = "\.xlsx$")
## allocate memory for our list
out <- vector("list", length(file_names)) 
## read the files and assign them to the list
for(i in seq_along(file_names)) {
    out[[i]] <- read.xlsx(file_names[i], startRow = 1, endRow = 100)  
}

或者您可以通过将 for() 循环更改为

来创建命名列表
for(file in file_names) {
    out[[file]] <- read.xlsx(file, startRow = 1, endRow = 100)  
}

在搜索相同内容时遇到此问题 - 这已添加到最新的 readxl 更新中。要获得 sheet 中的前 100 行,您可以

library(readxl)
file_names <- list.files(pattern = ".xlsx")

list_collection <- list() 
for(i in 1:length(file_names)){
  frame <- read_excel(file_names[i], n_max = 100)
  list_collection[i] <- list(frame)  
}

或者您可以使用类似

的方式指定特定的行
frame <- read_excel(file_names[i], range = cell_rows(1:100))