将多个表导入R中的多个数据框
问题描述:
我有一个带有大量工作表的Excel文件,我需要一个代码来将每张工作表导入到一个单独的数据框中,该数据框将按照与Excel中工作表名称相同的约定命名。将多个表导入R中的多个数据框
例如,标签A,B,C将分别作为数据框A,B和C导入。
从其他线程,我见过这样的代码: length(excel_sheets(filename))
获取文件中的张数
然后创建一个将包含每个选项卡的列表:
read_excel_allsheets <- function(filename) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
names(x) <- sheets
x
}
但我不知道如何从那里将制表符导入到R中。
将不胜感激的帮助。 在此先感谢!
答
下面是做这件事:
# write test data
tf <- writexl::write_xlsx(
list("the mtcars" = mtcars, "iris data" = iris),
tempfile(fileext = ".xlsx")
)
# read excel sheets
sheets <- readxl::excel_sheets(tf)
lst <- lapply(sheets, function(sheet)
readxl::read_excel(tf, sheet = sheet)
)
names(lst) <- sheets
# shove them into global environment
list2env(lst, envir = .GlobalEnv)
答
你的功能在所有选项卡中读取并保存为(因为lapply()
)一个列表的元素。你可以取出列表中的元素与list2env
:
your_excel_list <- read_excel_allsheets("test.xlsx")
list2env(your_excel_list, .GlobalEnv)
你会看到你的列表的命名元素现在的数据帧(或实际tbl_df
)在全球环境