重复使用其输出作为自己输入的 R 函数 [英] R function that uses its output as its own input repeatedly
问题描述
给定 R 函数 auto
(如下),我想知道是否有可能从 ps
for 循环输出的第二次运行开始code> 用作 pr
?
Given R function auto
(below), I was wondering if it might be possible that from the second run of the for
loop output of ps
be used as pr
?
例如,如果循环要进行 3 次(即 length(n) = 3
),则在循环的第一次运行中使用 pr
照原样,但是从第二次运行开始,之前运行的 ps
(即 ps(x)
)的结果取代了 pr
最多length(n)
个.
For example, if loop is going to go 3 times (i.e., length(n) = 3
), then in the first run of the loop pr
is used as is, but from the second run the result of ps
(i.e., ps(x)
) from the run before takes the place of pr
up to the number of length(n)
.
所以,在第一次运行 for
循环之后,每次,来自前一次运行的 ps(x)
都扮演了 pr
为下一次运行.我的最终目标是将这种方式得到的最终ps
曲线
.
So, after the first run of the for
loop, each time, ps(x)
from the previous run takes the role of pr
for the next run. My ultimate goal is to curve
the final ps
obtained in this manner.
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`.
推荐答案
不确定我是否完全理解问题.我在 for 循环中添加了一个 if 语句来检查它是否是第一次迭代.如果是,它将通过您的原始语句定义 pr
.如果不是,则通过 pr(x) * 由 i-1
子集的前一次迭代的 lk(x) 函数定义它.不过我确定我在这里遗漏了一些东西..
Not sure I fully understand the problem. I added an if statement in the for loop to check if its the first iteration. If it is, it would define pr
, by your original statement. if not, define it by pr(x) * the lk(x) function of the previous iteration which subsets by i-1
. I'm sure I'm missing something here though..
我也很困惑 x 输入的来源.
I'm also confused where the x input is coming from.
auto <- function(n, dat){
for(i in 1:length(n)){
if(i == 1){pr = function(x) dbeta(x, 1, 1)} else{pr = function(x) dbeta(x, 1, 1) * function(x) dbinom(dat[i-1], n[i-1], x)}
lk = function(x) dbinom(dat[i], n[i], x)
ps = function(x) pr(x)*lk(x)
}
curve(ps)
}
# Example of use:
auto(n = c(100, 50), dat = c(55, 60) )
这篇关于重复使用其输出作为自己输入的 R 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!