本文介绍了R函数重复使用其输出作为自己的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 给定R函数 auto (下面),我想知道是否有可能从的第二次运行中为循环输出 ps 用作 pr ? 例如,如果循环要执行3次(即 length(n)= 3 ),那么在循环的第一次运行 pr 按原样使用,但从第二次运行得到 ps (即 ps(x) )取代 pr 到 length(n) ps(x)从上一次运行中起到下一次运行的角色 pr 。我的最终目标是以这种方式获得的曲线最终的 ps 。 pre $ auto for(i in 1:length(n)){ pr =函数(x)dbeta(x,1,1) lk =函数(x)dbinom(dat [i],n [i],x)所以,这里首先是`n = 100`和 ps = function(x)pr(x)* lk(x)#`dat = 55`将通过循环的第一个}#循环并产生曲线(ps)#a` ps`。但是在#循环的第二次运行中,`ps`只是#使用示例:#products将被用作`pr` auto(n = c(100, 50),dat = c(55,60))#为`n = 50`和`dat = 60` #来产生一个新的`ps`。 解决方案不知道我完全理解了这个问题。我在for循环中添加了一个if语句来检查它是否是第一次迭代。如果是的话,它会根据您的原始语句定义 pr 。如果不是,则用pr(x)*前一次迭代的lk(x)函数来定义它,它由 i-1 子集。我确信我在这里失去了一些东西。 我也很困惑x输入是从哪里来的。 auto< - 函数(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 =函数(x)dbinom(dat [i],n [i],x) ps = function(x)pr(x)* lk(x)} curve(ps)} #使用示例: auto(n = c(100,50),dat = c(55,60)) 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?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).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`. 解决方案 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..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函数重复使用其输出作为自己的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 06:18