在Wolfram Mathematica中,函数NestList[f,x,n]
生成长度为n+1
的向量输出,并在变量f
上多次应用函数x
。请参阅documentation。
R中有类似的东西吗?
执行do.call
会多次进行相同的计算。
示例(对USER_1建议的反应):
foo <- function(x) {x+1}
map(0, foo)
# [[1]]
# [1] 1
答案 0 :(得分:1)
只写一个。这样的函数无论如何都必须循环(如果n可以变大,则不建议使用递归)。
NestList <- function(f, x, n) {
stopifnot(n > 0)
res <- rep(x, n + 1)
if (n == 1L) return(res)
for (i in seq_len(n)) res[i+1] <- f(res[i])
res
}
NestList(function(x) x^2, 2, 5)
#[1] 2 4 16 256 65536 4294967296