我是 R 编程新手。现在,我有一个 Excel 文件 (.xlsx),里面有 3 张纸。我想使用
for
循环创建 3 个数据框,每个数据框对应 Excel 文件中的一张表。
我使用
library(readxl)
和 read_excel()
来读取文件
首先,我创建了名为
result
的列表,并使用下面的代码将 3 张表中的数据导入到列表中
library(readxl)
result <- list()
for (i in 1:3) {
result[[i]] <- read_excel("students.xlsx", sheet = i)
}
接下来,我想从列表中创建 3 个数据框,并用工作表的名称命名数据框,但我不知道下一步要做什么才能使代码正常工作。
接下来我可以尝试什么?
请尝试以下代码
# get the names of the excel sheets
name_excel <- readxl::excel_sheets('C:\\Users\\Documents\\example.xlsx')
# custom function to read the data from the individual sheet of the excel file
read_excel <- function(x){
excel <- readxl::read_xlsx('C:\\Users\\Documents\\example.xlsx', sheet = x)
assign(x,excel, envir = globalenv())
}
# generate separate data frames of each individual sheet
purrr::map(name_excel, read_excel)
创建于 2023-11-09,使用 reprex v2.0.2