在 for 循环 R 中从 `curve()` 中保存 x 和 y?

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

我有一个名为 all.priors 的函数(参见下面的 R 代码)。我的目标是从 for 循环中的 curve() 调用中获取 xy,并保存这些 xy作为对象 h.

(我想在 h 中有 101 行和 2*length(d) 列。这样,每 2 列包含 xy来自 for 循环中的 curve() 运行。)

问题:

如何正确保存 curve() 调用中的 xy? [我收到错误: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"))

您只需要小心地将值放在矩阵中,然后 return 来自您的函数的矩阵。试试这个

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

解决此问题的另一种方法可能是将答案保存在列表中而不是矩阵中。我认为您的功能使正在发生的事情变得复杂,因此我将使用一个更简单的示例。

h = list()
for(i in 1:5) {
    h[i] = list(curve(sin(i*x), xlim=c(0,6.3))) }

生成的数据结构应该易于使用。