[英]File name as legitimate column in R data frame
我正在將一個文件夾中所有XLS文件中的一張合並到一個數據框中,並顯示所有這些文件中的特定范圍,效果很好。 但是,我想將文件名添加為實際的列,該列現在不起作用-它顯示為行而不添加列。
屏幕截圖可以幫助我理解更多內容。 您可以看到第2 2列具有標題,但第2列沒有標題,因此,如果我添加了導出到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)
我知道了。 文件名是第一列,我將范圍縮小到一個單元格,因為我需要的其他所有內容都在文件名本身中。
#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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.