簡體   English   中英

R:如何將遞歸或迭代函數/映射輸出輸出到向量中?

[英]R: How to output a recursive or iterative function/map output into a vector?

我想將用戶定義函數的輸出反饋回其輸入(遞歸映射),運行此迭代N次,並將每次迭代的輸出保存在向量中。 這對於“ for”循環很簡單

my_fun <- function(x) {x/3 +1} # a user-defined function (trivial example)

my_l <- c()

x <- 0 # initial condition

for(i in 1:10) {
  x <- my_fun(x)
  my_l[i] <- x
}

print(my_l)

>[1] 1.000000 1.333333 1.444444 1.481481 1.493827 1.497942 1.499314 1.499771 1.499924 1.499975

上面的作品,但似乎很粗糙。 有更短的方法嗎? 也許有tidyverse / purrr?

我們可以使用accumulate

library(tidyverse)
accumulate(1:10, ~ my_fun(.x), .init = 1)
#[1] 1.000000 1.333333 1.444444 1.481481 1.493827 1.497942 1.499314 1.499771 1.499924 1.499975 1.499992

或從base R Reduce

Reduce(function(x, y) my_fun(x), 1:10, init = 1, accumulate = TRUE)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM