gpt4 book ai didi

r - 对数据应用函数 n 次

转载 作者:行者123 更新时间:2023-12-01 08:22:12 25 4
gpt4 key购买 nike

我想每次都使用函数的输出在向量上应用相同的函数一定次数。

一个带有简单函数的简化示例只是为了演示:

# sample vector
a <- c(1,2,3)

# function to be applied n times
f1 <- function(x) {
x^2 + x^3
}

我想在 f1 上应用 an 次数,例如这里可以说 3 次。

我听说 purrr::reducepurrr::map() 可能是一个好主意,但无法使其工作。

如果 n = 3 等于 f1(f1(f1(a))) ,则所需的输出。

最佳答案

让我们使用Reduce(没有外部库要求,一般性能良好)。我将稍微修改函数以接受第二个(被忽略的)参数:

f1 <- function(x, ign) x^2 + x^3

Reduce(f1, 1:3, init = a)
# [1] 1.872000e+03 6.563711e+09 1.102629e+14

这就是正在发生的事情。 Reduce :

uses a binary function to successively combine the elements of a given vector and a possibly given initial value.



第一个参数是要使用的函数,它应该接受两个参数。第一个是此归约中先前执行函数的值。在第一次调用该函数时,它使用提供的 init= 值。
  • 第一次调用:
    f1(c(1,2,3), 1)
    # [1] 2 12 36
  • 第二次调用:
    f1(c(2,12,36), 2)
    # [1] 12 1872 47952
  • 第三次调用:
    f1(c(12,1872,47952), 3)
    # [1] 1.872000e+03 6.563711e+09 1.102629e+14

  • 第二个参数 1:3 仅用于其长度。任何长度合适的东西都可以。

    如果你不想为了这个减少而重新定义 f1,你可以随时做
    Reduce(function(a,ign) f1(a), ...)

    基准:
    library(microbenchmark)
    r <- Reduce(function(a,b) call("f1", a), 1:3, init=quote(a))
    triple_f1 <- function(a) f1(f1(f1(a)))
    microbenchmark::microbenchmark(
    base = Reduce(function(a,ign) f1(a), 1:3, a),
    accum = a %>% accumulate(~ .x %>% f1, .init = f1(a)) %>% extract2(3),
    reduc = purrr::reduce(1:3, function(a,ign) f1(a), .init=a),
    whil = {
    i <- 1
    a <- c(1,2,3)
    while (i < 10) {
    i <- i + 1
    a <- f1(a)
    }
    },
    forloop = {
    out <- a
    for(i in seq_len(3)) out <- f1(out)
    },
    evaluated = {
    r <- Reduce(function(a,b) call("f1", a), 1:3, init=quote(a))
    eval(r)
    },
    precompiled = eval(r),
    anotherfun = triple_f1(a)
    )
    # Unit: microseconds
    # expr min lq mean median uq max neval
    # base 5.101 7.3015 18.28691 9.3010 10.8510 848.302 100
    # accum 294.201 328.4015 381.21204 356.1520 402.6510 823.602 100
    # reduc 27.000 38.1005 57.55694 45.2510 54.2005 747.401 100
    # whil 1717.300 1814.3510 1949.03100 1861.8510 1948.9510 2931.001 100
    # forloop 1110.001 1167.1010 1369.87696 1205.5010 1292.6500 9935.501 100
    # evaluated 6.702 10.2505 22.18598 13.3015 15.5510 715.301 100
    # precompiled 2.300 3.2005 4.69090 4.0005 4.5010 26.800 100
    # anotherfun 1.400 2.0515 12.85201 2.5010 3.3505 1017.801 100

    关于r - 对数据应用函数 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954442/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com