在列表列表中加入数据 [英] Joining data in lists of list
问题描述
我正在使用readxl包从多个Excel文件中导入数据,并且在脚本中创建了一个函数,以便仅导入所需的特定工作表
I'm importing data from multiple excel files using the readxl package and I made a function in my script so that I only import specific sheets that I need
read_excel_sheets <- function(excelDoc) {
sheets <- readxl::excel_sheets(excelDoc)
sheets <- sheets[4:6]
x <- lapply(sheets, function(X) readxl::read_excel(excelDoc, sheet = X))
return(x)
}
#load files in folder
rawfiles <- list.files()
IMPORT <- lapply(rawfiles, FUN = read_excel_sheets)
将文件夹中的文件加载到脚本中后,IMPORT成为列表[10],其中包含list [3],基本上是列表内部的列表.
After loading the files in my folder into my script, IMPORT becomes a list[10] that contains list[3] inside of it, basically lists inside of a list.
不幸的是,我无法使用reduce(full_join)将数据收集到一个数据表中.我尝试只使用一个excel文件并使用unlist()来查看是否可以将我的工作表从列表列表中删除,但这不起作用.
Unfortunately, I can't use reduce(full_join) to gather my data into one data table. I've tried working with just one excel file and using unlist() to see if I can get my sheets out of the lists of list but that did not work.
Test <- read_excel_sheets("Hop_L_Trial1.xlsx")
Test_Test <- unlist(Test)
我也尝试过
rawfiles <- list.files()
IMPORT <- lapply(rawfiles,
FUN = read_excel_sheets)
Test_3 <- rbindlist(IMPORT)
并收到错误消息项目1的第1列的长度2与长度2的第2列不一致.仅长度为1的列被回收."谢谢您关于如何将我的数据合并到一个数据表中的任何建议.
and received an error "Column 1 of item 1 is length 2 inconsistent with column 2 which is length 6. Only length-1 columns are recycled." Any suggestions on how to join my data into one data table would be greatly appreciated, thank you.
推荐答案
您可以使用purrr
中的map_df
将数据作为单个数据帧获得.
You can use map_df
from purrr
to get data as a single dataframe.
read_excel_sheets <- function(excelDoc) {
sheets <- readxl::excel_sheets(excelDoc)
sheets <- sheets[4:6]
x <- purrr::map_df(sheets, function(X) readxl::read_excel(excelDoc, sheet = X))
return(x)
}
IMPORT <- purrr::map_df(rawfiles, FUN = read_excel_sheets)
您还可以使用do.call
+ rbind
基本R函数.
You can also use do.call
+ rbind
base R functions.
read_excel_sheets <- function(excelDoc) {
sheets <- readxl::excel_sheets(excelDoc)
sheets <- sheets[4:6]
x <- do.call(rbind, lapply(sheets, function(X) readxl::read_excel(excelDoc, sheet = X)))
return(x)
}
IMPORT <- do.call(rbind, lapply(rawfiles, FUN = read_excel_sheets))
这篇关于在列表列表中加入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!