本文介绍了在for循环R中,将`curve()`中的x和y保存起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个名为 code> s作为对象 h 。 (我想要 101 行和 2 * length(d)列中的 h 。 2列包含 x 和 y 来自 curve()在中运行循环。) 问题: 如何正确保存 x s和 y code> curve()调用? [我得到错误:矩阵上的下标数量不正确] all.priors =函数(a,b,lo,hi,d,Bi = 55,n = 1e2){ $ bh =矩阵(NA,101,2 *长度(d))$ b $ ($) =函数(x)得到(d [i])(x,a,b) prior =函数(x) p(x)/ integrate(p,lo,hi)[[1]] 似然函数(x​​)dbinom(Bi,n,x) posterior =函数(x) *可能性(x)h [i,] =曲线(posterior,ty =n,ann = FALSE,yaxt =n,xaxt =n,add = i!= 1,bty = $ b#使用示例: all.priors(lo = 0,hi = 1,a = 2,b = 3,d = c dgammadnormdcauchydlogis)) 解决方案你只需要仔细地将值放在矩阵中,然后从你的函数返回矩阵。 (a,b,lo,hi,d,Bi = 55,n = 1e2) { $ bh =矩阵(NA,101,2 *长度(d)) (i为1:长度(d)){p =函数(x,a),b(b,b)先验函数(x)p(x)/ integral(p,lo,hi)[b]函数(x)dbinom(Bi,n,x) posterior = function(x)prior(x)* likelihood(x) cv h [,i * 2-1] h [,i * 2] } h } all.priors(lo = 0,hi = 1,a = 2,b = 3, d = c(dgamma,dnorm,dcauchy,dlogis)) 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")) 解决方案 You just need to carefully place the values in the matrix, and then return the matrix from your function. try thisall.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")) 这篇关于在for循环R中,将`curve()`中的x和y保存起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 21:55