请考虑以下三个功能:
f1 <- function(df, ...) {
df %>%
mutate(
model = map(.$splits, ~ f2(.))
)
}
f2 <- function(split_df) {
split_df %>%
analysis() %>%
nest() %>%
mutate(
forecast = map(data, ~ f3(.$actuals))
)
}
f3 <- function(x, N = 3, fn = mean, window_size = 6, ...) {
# stuff
}
我正在较大的管道中运行这些功能,但我的问题的要点是:我想将参数传递给f3()
(例如,将fn = mean
更改为fn = median
下面的代码行:
df_resamples %>%
mutate(
result = .$resamples %>% map(~ f1(.))
)
但是,以下两个都不返回正确的结果:
# INCORRECT
df_resamples %>%
mutate(
result = .$resamples %>% map(~ f1(.), fn = median)
)
# ALSO INCORRECT
df_resamples %>%
mutate(
result = .$resamples %>% map(~ f1(., fn = median))
)
如果我在fn
中对f2
进行硬编码,则会得到正确的结果:
f2_good <- function(split_df) {
split_df %>%
analysis() %>%
nest() %>%
mutate(
forecast = map(data, ~ f3(.$actuals, fn = median))
)
}
fn = median
传递f3
,怎么不能将...
传递给f1
?
注意:我能够解决将参数传递到f1
和f2
的问题,但这并不十分干,我想我可以使用省略号来规避这种方法:< / em>
f1 <- function(df, N = 3, fn = mean, window_size = 6) {
df %>%
mutate(
model = map(.$splits, ~ f2(., N = N, fn = fn, window_size = window_size))
)
}
f2 <- function(split_df, N = 3, fn = mean, window_size = 6) {
split_df %>%
analysis() %>%
nest() %>%
mutate(
forecast = map(data, ~ f3(.$actuals, N = N, fn = fn, window_size = window_size))
)
}
这样做,我就能做到:
df_resamples %>%
mutate(
result = .$resamples %>% map(~ f1(., fn = median))
)
并获得预期的结果,但是我必须将默认值传递给f1
和f2
...
答案 0 :(得分:0)
您是否尝试过将...
添加到每个签名和函数调用中,例如:
f1 <- function(df, ...) {
df %>%
mutate(
model = map(.$splits, ~ f2(., ...))
)
}
f2 <- function(split_df, ...) {
split_df %>%
analysis() %>%
nest() %>%
mutate(
forecast = map(data, ~ f3(.$actuals, ...))
)
}
f3 <- function(x, N = 3, fn = mean, window_size = 6, ...) {
# stuff
}
然后致电
df_resamples %>%
mutate(
result = .$resamples %>% map(~ f1(., fn = median))
)
编辑:玩具示例
f1 <- function(x, ...) f2(x, ...)
f2 <- function(x, ...) f3(x, ...)
f3 <- function(x, fn = mean, na.rm = FALSE, ...) fn(x, na.rm = na.rm)
f1(c(1,2,3,NA), fn = max, na.rm = TRUE)