R function that uses its output as its own input repeatedly

后端 未结 3 2079
醉梦人生
醉梦人生 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:48

    I thought to use a different way. Although, I have not completed it but still thought to share with others for improvement ideas. I'm looking at very basic and crude way to solve it.

    auto <- function(n, dat){
      pr = function(x) dbeta(x, 1, 1)
      lk = function(x) dbinom(dat[1], n[1], x)
      ps = function(x) pr(x)*lk(x) 
      #keep the funtion till now in psold 
      psold = ps
      #loop through 2nd to 2nd last element
      for(i in 2:length(n)-1){
        lk = function(x) dbinom(dat[i], n[i], x)
        #Use psold to evaluate new function ps
        ps = function(x) psold(x)*lk(x)
        psold = ps
      }
      lk = function(x) dbinom(dat[length(n)], n[length(n)], x)
      #Finaly function to be returned.
      ps = function(x) psold(x)*lk(x)  
    }
    # Example of use:
    auto(n = c(100, 50), dat = c(55, 60) )
    

提交回复
热议问题