如何将以特定字母开头的 excel 文件中的所有工作表组合在一起?
How do I combine all sheets in an excel file that begin with a specific letter?
我有一个包含 20 多个标签的 excel 文件。我想将所有选项卡导入并组合到一个数据框中,但只导入以特定字母系列开头的选项卡。相关的标签都是以“AB”开头,后面是一串数字。我想合并所有以“AB”开头的选项卡
您可以将 lapply
与 grep
结合使用并使用 readxl
包导入:
library(readxl)
# Since no data were given, using embedded sample data
xlsx_example <- readxl_example("datasets.xlsx") # path to sample data
# [1] "/Library/Frameworks/R.framework/Versions/4.1/Resources/library/readxl/extdata/datasets.xlsx"
# get all the sheets:
allsheets <- excel_sheets(xlsx_example)
# [1] "iris" "mtcars" "chickwts" "quakes"
# grep with only the pattern you want
# here, I will select sheet names with an "i" in it
sheet_list <- lapply(allsheets[grep("i",allsheets)], function(x) read_excel(xlsx_example, sheet = x))
这会为您提供一个列表,其中包含您选择的工作表。如果您希望该列表中的每个元素都进入全局环境,请执行;
names(sheet_list) <- allsheets[grep("i",allsheets)]
list2env(sheet_list, .GlobalEnv)
您也可以使用 for
循环将它们直接分配给全局环境:
for(xx in grep("i",allsheets)){
assign(allsheets[xx], read_excel(xlsx_example, sheet = allsheets[xx]))
}
我有一个包含 20 多个标签的 excel 文件。我想将所有选项卡导入并组合到一个数据框中,但只导入以特定字母系列开头的选项卡。相关的标签都是以“AB”开头,后面是一串数字。我想合并所有以“AB”开头的选项卡
您可以将 lapply
与 grep
结合使用并使用 readxl
包导入:
library(readxl)
# Since no data were given, using embedded sample data
xlsx_example <- readxl_example("datasets.xlsx") # path to sample data
# [1] "/Library/Frameworks/R.framework/Versions/4.1/Resources/library/readxl/extdata/datasets.xlsx"
# get all the sheets:
allsheets <- excel_sheets(xlsx_example)
# [1] "iris" "mtcars" "chickwts" "quakes"
# grep with only the pattern you want
# here, I will select sheet names with an "i" in it
sheet_list <- lapply(allsheets[grep("i",allsheets)], function(x) read_excel(xlsx_example, sheet = x))
这会为您提供一个列表,其中包含您选择的工作表。如果您希望该列表中的每个元素都进入全局环境,请执行;
names(sheet_list) <- allsheets[grep("i",allsheets)]
list2env(sheet_list, .GlobalEnv)
您也可以使用 for
循环将它们直接分配给全局环境:
for(xx in grep("i",allsheets)){
assign(allsheets[xx], read_excel(xlsx_example, sheet = allsheets[xx]))
}