Search code examples
rfunctionfor-loopcurve

Saving x, and y from `curve()` in a for loop R?


I have a function called all.priors (see R code below). My goal is to get the x and y from the curve() call inside the for loop, and save these xs and ys as object h.

(I want to have 101 rows, and 2*length(d) columns in h. This way, each 2 columns, contain x and y from a curve() run in the for loop.)

Question:

how can I correctly save the xs and ys from the curve() call? [I get the error: incorrect number of subscripts on matrix]

all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = matrix(NA, 101, 2*length(d)) 

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
     h[i,] = curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
     }
}
#Example of use:
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))

Solution

  • You just need to carefully place the values in the matrix, and then return the matrix from your function. try this

    all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){
    
      h = matrix(NA, 101, 2*length(d)) 
    
      for(i in 1:length(d)){
        p = function(x) get(d[i])(x, a, b)
        prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
        likelihood = function(x) dbinom(Bi, n, x)
        posterior = function(x) prior(x)*likelihood(x)
        cv <- curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
        h[,i*2-1] <- cv$x
        h[,i*2] <- cv$y
      }
      h
    }
    all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))