0

我将文件夹中所有 XLS 文件中的一张表合并到一个数据框中,并显示所有这些文件中的特定范围,效果很好。但是,我想将文件名添加为实际列,这现在不起作用 - 它显示为行而不添加列。

屏幕截图可能会帮助我更有意义。您可以看到第二两列有标题,但第一列没有,所以如果我添加导出到 Excel 等的功能,该列将丢失。

数据框

代码:

#library
library(readxl)
library(plyr)

#define path
# setwd
my_path <- file.path("C:", "File", "Path")
setwd(my_path)

# list all files in the directory
data.files = list.files()

# list all files in the directory ending with .xls
wb <- list.files(pattern = "*.xls")

# create an empty list
dflist <- list()

# populate dflist with wb
for (i in wb){
  dflist[[i]] = data.frame(read_excel(i, sheet = "Sheet1", range = "C15:D16", col_names = FALSE, row.names(data.files)))
}

#create final data frame, bind dflist
OBJDList = do.call(what = rbind, args = dflist)
4

1 回答 1

0

我让它工作。文件名是第一列,我将范围缩小到一个单元格,因为我需要的所有其他内容都在文件名本身中。

#library
library(readxl)
library(plyr)
library(xlsx)
library(data.table)

#define path
my_path <- file.path("G:", "your", "path")
setwd(my_path)

# list all files in the directory
data.files = list.files()

# list all files in the directory ending with .xls
wb <- list.files(pattern = "*.xls")

# create an empty list
dflist <- list()

# populate dflist with wb
for (i in wb){
  dflist[[i]] = data.frame(read_excel(i, sheet = "sheet1", range = "D16", col_names = FALSE, row.names(data.files)))
}



#create final data frame, bind dflist
OBJDList = do.call(what = rbind, args = dflist)

setDT(OBJDList, keep.rownames = TRUE)[]

OBJDList

print(OBJDList)

write.xlsx(OBJDList, file = "G:/your path/yourfile.xlsx",
           sheetName = "Sheet1", append = FALSE)
于 2018-04-05T13:02:19.973 回答