R, which uses its output as its own input repeatedly

Given the function R auto(see below), I was wondering if it is possible that from the second run of the output cycle forfor pswill be used like pr?

For example, if the cycle will go 3 times (i.e. length(n) = 3), then in the first run of the cycle it is prused as is, but from the second run the result ps(i.e. ps(x)) from run to the place prto the number length(n).

So, after the first run of the cycle, foreach time ps(x)from the previous run, it takes on a role prfor the next run. My ultimate goal is to get the curvefinal ps, obtained in this way.

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`.
+1
3

.

, -, , . , . . , switch .

auto <- function(n, dat, n.loop){
x <- 0.1;
for(i in 1:n.loop){
val <- switch(i, dbeta(x, 1, 1), dbinom(dat, n, x), dbeta(x, 1, 1)*dbinom(dat, n, x))
print(val);
  }
}

auto(n = 100, dat = 55, n.loop = 3)

2 , . 1) x , auto? , x auto . , ? 2) ?

, x <- 0.1 print(val).

0

. , , . .

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

, . if for, , . , pr . , pr (x) * lk (x) , i-1. , - ...

, .

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

Source: https://habr.com/ru/post/1676706/


All Articles