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
Let me try to give an answer.
So, firstly, I thought, that you need finite state automata function. This approach needs to use environment usage in which you need to store state and values for your functions call.
But, you need only make choice based on your cycle index value.
It's much easier, because you need only switch
operator and nothing more.
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)
I have 2 questions which should reorganize code well.
1) What is an x
value which you use in auto? This is not an argument in your code, so, you should determine value of x
in auto
directly. Maybe is this an argument?
2) What value does your function need to return as a value?
So, x <- 0.1
and print(val)
were added for checking code execution.
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) )
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) )