R function that uses its output as its own input repeatedly

后端 未结 3 2078
醉梦人生
醉梦人生 2020-12-11 12:59

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 a

3条回答
  •  天涯浪人
    2020-12-11 13:34

    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) )
    

提交回复
热议问题