我想为内部函数定义一个包装器。其思想是重复使用r*基函数之一的随机抽样(如runif、rnorm等)。让用户轻松地更改这个内部函数并定义自定义函数。
下面的示例显示了一个可重复的示例,我无法使用tidyeval模式,更确切地说,是在purrr::map中工作。...的评价似乎不恰当。我漏掉了一些关于商评的东西,但我想不出是什么。我还在下面展示了一个解决方法,它可以很好地处理古尔德的旧replicate。
我想在更复杂的情况下实施这种行为,更广泛地说,我很高兴看到任何指示,并理解为什么以下内容不起作用。
# use the tidyverse and define a dummy tibble
library(tidyverse)
df <- tibble(col1=seq(10, 50, 10), col2=col1+5)
# first random function, on top of stats::runif
random_1 <- function(x, min, max){
x %>%
rowwise() %>%
mutate(new=runif(1, min={{min}}, max={{max}})) %>%
ungroup()
}
# second random function, on top of stats::rnorm
random_2 <- function(x, mean, sd){
x %>%
rowwise() %>%
mutate(new=rnorm(1, mean={{mean}}, sd={{sd}})) %>%
ungroup()
}
# at top level, everything works fine
> df %>% random_1(min=col1, max=col2)
> df %>% random_2(mean=col1, sd=col2)
# So far so good
# we we wrap it for a single shot
random_fun <- function(x, random_fun, ...){
random_fun(x, ...)
}
random_fun(df, random_1, min=col1, max=col2)
# Still fine.
# Here comes the trouble:
random_fun_k <- function(df, k, random_fun, ...){
map(1:k, ~random_fun(df, ...))
}
random_fun_k(df, k=2, random_1, min=col1, max=col2)is_quosure(x)中的错误:参数"x“缺失,没有默认情况
围绕replicate的以下解决方法工作得很好,但我还是想坚持使用tidyeval精神:
random_fun_k_oldie <- function(df, k, random_fun, ...){
f <- random_fun(df, ...)
replicate(k, f, simplify=FALSE)
}
random_fun_k_oldie(df, k=2, random_1, min=col1, max=col2)
random_fun_k_oldie(df, k=2, random_2, mean=col1, sd=col2)发布于 2022-04-17 18:05:12
最好使用原始lambda函数,即function(x)。
library(purrr)
random_fun_k <- function(df, k, random_fun, ...){
map(seq_len(k), function(x) random_fun(df, ...))
}-testing
> random_fun_k(df, k=2, random_1, min=col1, max=col2)
[[1]]
# A tibble: 5 × 3
col1 col2 new
<dbl> <dbl> <dbl>
1 10 15 12.6
2 20 25 21.4
3 30 35 34.1
4 40 45 40.7
5 50 55 53.8
[[2]]
# A tibble: 5 × 3
col1 col2 new
<dbl> <dbl> <dbl>
1 10 15 13.1
2 20 25 24.2
3 30 35 33.8
4 40 45 41.6
5 50 55 50.9注意:函数名和参数名似乎是相同的rand_fun,这也可能导致一些混淆(尽管它不是错误的来源)。最好用不同的方式重命名函数参数。
random_fun <- function(x, rn_fun, ...){
rn_fun(x, ...)
}发布于 2022-04-19 06:56:33
purrr的lambda支持使用..1、..2等语法的位置参数。这是通过...机制实现的。正因为如此,您没有将正确的参数传递给random_fun。
解决方案是使用正常的lambda函数,就像akrun建议的那样。也许您可以使用R4.0的\(x) x语法。
https://stackoverflow.com/questions/71904154
复制相似问题