【发布时间】:2020-02-03 05:22:09
【问题描述】:
我正在尝试创建一个函数,该函数使用 readxl::read_excel 读取 excel 工作簿中的所有工作表并将它们绑定到单个数据框中,并允许我将其他参数传递给 read_excel。我可以很好地完成第一部分,但不能完成第二部分。
library(magrittr)
# example excel workbook with multiple sheets
path <- readxl::readxl_example("datasets.xlsx")
# function with simple forwarding
read_all <- function(path, ...) {
path %>%
readxl::excel_sheets() %>%
rlang::set_names() %>%
purrr::map_df(~ readxl::read_excel(path = path, sheet = .x, ...))
}
# errors with and without additional arguments
read_all(path)
read_all(path, skip = 5)
我应该取回一个文件,但我得到一个错误:
Error: Can't guess format of this cell reference: iris
In addition: Warning message: Cell reference follows neither the A1 nor R1C1 format. Example: iris NAs generated.
没有参数传递函数可以正常工作:
# Function works without passing extra params
read_all_0 <- function(path) {
path %>%
readxl::excel_sheets() %>%
rlang::set_names() %>%
purrr::map_df(~ readxl::read_excel(path = path, sheet = .x))
}
read_all_0(path)
在没有purrr::map_df 的简单函数中,参数传递可以正常工作
read_test <- function(path, ...) {
path %>% readxl::read_excel(...)
}
read_test(path, skip = 10)
【问题讨论】:
-
您可以尝试:(1) 在您的地图调用中使用普通匿名函数
function(x) {},而不是lamda 函数符号~。如果错误仍然显示 (2) 在set_names之后省略管道并使用中间变量。 -
没有骰子。仍然收到相同的错误消息。
doc <- path %>% readxl::excel_sheets() %>% rlang::set_names()和purrr::map_df(doc, function(x) {readxl::read_excel(path = path, sheet = .x, !!!args)})}``` -
您错误地指定了匿名函数。如果您使用
function(x),则必须将.x替换为x。请参阅下面的回复。