文件名为R数据框中的合法列

时间:2018-04-03 17:49:36

标签: r readxl

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

截图可能会让我更有意义。您可以看到第2列有标题,但第一列没有,所以如果我添加了导出到Excel等功能,那么该列将会丢失。

dataframe

代码:

#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)

1 个答案:

答案 0 :(得分:0)

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

#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)