【发布时间】:2018-05-31 03:44:50
【问题描述】:
给定 R 函数 auto(如下),我想知道是否有可能从第二次运行 for 循环输出 ps 被用作 pr?
例如,如果循环要运行 3 次(即,length(n) = 3),那么在循环的第一次运行中,pr 将按原样使用,但从第二次运行开始,ps 的结果(即,ps(x)) 从之前的运行中取代pr 直到length(n) 的数量。
因此,在for 循环的第一次运行之后,每次,上一次运行中的ps(x) 都会在下一次运行中扮演pr 的角色。我的最终目标是curve最终以这种方式获得的ps。
auto <- function(n, dat){
for(i in 1:length(n)){
pr = function(x) dbeta(x, 1, 1)
lk = function(x) dbinom(dat[i], n[i], x) # So, here first `n = 100` and
ps = function(x) pr(x)*lk(x) # `dat = 55` will go thru first
} # round of the loop and produce
curve(ps) # a `ps`. But in the second run of
} # the loop, the `ps` just
# Example of use: # produced will be used as `pr`
auto(n = c(100, 50), dat = c(55, 60) ) # for `n = 50` and `dat = 60`
# to produce a new `ps`.
【问题讨论】:
-
你是在问如何写一个递归函数?
-
我不明白这个问题,但这里有一个递归定义函数的例子:
factorial <- function(x) if (x==0) return(1) else return(x*factorial(x-1)); factorial(5)。这些在 R 中通常效率不高,并且堆栈深度有限制。 -
你想从
function返回function吗?如果是,那么您只能返回 1 个函数。您帖子中的ps。现在有什么问题? -
我认为他想在运行后更改
for运算符中的功能 -
R 中的 @morouzian 函数不是有限状态自动化。而且您没有像 C# 中那样用于状态保存的
yield关键字。可能,您可以在函数代码中使用函数名称并使用do.call运算符按名称调用。