我正在玩 purrr 的
map()
和 partial()
并想尝试创建一个具有预配置输入的函数列表,当我使用这些函数时,它将返回函数输出 AND 打印出函数的配置(也作为验证检查,以确保我已正确配置该功能)
我已经使用预配置的输入设置了每个功能,没有任何问题,但我无法让它向输入发送消息。
library(tidyverse)
#arbitrary sequence
n_vec <- seq(5,100,5)
mean_vec <- seq(50,1000,50)
# create list of functions that are pre-configured with various inputs
rnorm_lst <- map2(
.x=n_vec
,.y=mean_vec
,.f=\(.x,.y){
# When I use a function, I want it to message its input assumptions
print(.x)
print(.y)
# this is the underlying function that I want to create with partial
out <- partial(rnorm,n=.x,mean=.y)
return(out)
}
)
# create a name based on its configuration
names_lst <- paste0("n",n_vec,"_","mean",mean_vec)
# assign a name to each function
names(rnorm_lst) <- names_lst
# call a function to see if it works
rnorm_lst$n50_mean500()
此功能的
rnorm()
方面有效,但它不会打印或发送其输入消息。
我认为这与环境有关?但我不确定。
print(.x)
和print(.y)
是在定义rnorm_list
期间执行的,而不是在函数执行期间执行的。
我将
print()
移入新函数的定义中,然后将其输入到 partial()
:
library(purrr)
#>
#> Attaching package: 'purrr'
#> The following object is masked from 'package:base':
#>
#> %||%
n_vec <- seq(5,100,5)
mean_vec <- seq(50,1000,50)
# create list of functions that are pre-configured with various inputs
rnorm_lst <- map2(
.x=n_vec
,.y=mean_vec
,.f=\(.x,.y){
# this is the underlying function that I want to create with partial
new <- function(...) {
# When I use a function, I want it to message its input assumptions
print(.x)
print(.y)
rnorm(...)
}
return(partial(new, n = .x, mean = .y))
}
)
# create a name based on its configuration
names_lst <- paste0("n",n_vec,"_","mean",mean_vec)
# assign a name to each function
names(rnorm_lst) <- names_lst
# call a function to see if it works
rnorm_lst$n50_mean500()
#> [1] 50
#> [1] 500
#> [1] 499.7868 500.5834 500.0835 500.7119 500.0949 498.2750 498.4815 498.7130
#> [9] 499.7779 500.8300 500.8086 498.2535 500.4854 498.6614 501.3506 501.5732
#> [17] 500.3742 500.5254 499.3777 498.4927 499.7738 500.9925 499.4880 499.0919
#> [25] 500.4387 499.7716 500.7130 498.2386 500.1190 499.8829 499.2836 499.4103
#> [33] 499.5191 499.9471 499.8817 500.2749 499.9995 499.4147 500.4018 498.9776
#> [41] 499.6448 500.0447 500.4869 500.0282 499.4247 500.2372 500.5241 500.1198
#> [49] 500.4847 500.1996
创建于 2024-05-19,使用 reprex v2.1.0