【问题标题】:evaluating numerical integration for all sample observations评估所有样本观测值的数值积分
【发布时间】:2019-04-10 20:31:22
【问题描述】:

我需要以数值方式计算此积分,然后评估其每次观察的值。我尝试使用集成功能来做到这一点,但每次我收到错误消息。这是我的代码:

    `rm(list = ls(all = TRUE)) # Remove all objects in R console
set.seed(123456) # Set the seed for reproducible results.default for the program to fix initial values to start with in each time.
install.packages("MASS")
library (MASS)  ## Simulate from a Multivariate Normal Distribution
n=10 # sample size
mu=c(0.3,0.7029) # true values of the mean vector of bivariate normal variables
var.cov<-matrix(c(10,0,0,10),nrow=2,ncol=2,byrow=T) #variance covariance matrix of the bivariate normal random variables    
y= mvrnorm(n, mu, var.cov)#generating the bivariate normal random variables
theta.rad=rep(NA,times=n)
for (ii in 1:n){
  if (y[ii,1] > 0 & y[ii,2]>=0) {theta.rad[ii]=atan(y[ii,2]/y[ii,1])}
  else if (y[ii,1] < 0) {theta.rad[ii]=(atan(y[ii,2]/y[ii,1]))+pi}
  else if (y[ii,1] > 0 & y[ii,2]<0) {theta.rad[ii]=atan(y[ii,2]/y[ii,1])+2*pi}
  else if (y[ii,1] == 0 & y[ii,2]>0) {theta.rad[ii]=pi/2}
  else if (y[ii,1] ==0 & y[ii,2]<0) {theta.rad[ii]=3*pi/2}
}# calculating the angles
u=cbind(cos(theta.rad),sin(theta.rad)) #constructing the main matrix (cos(theta,sin(theat)))
integral=function(uu){
  f=function(r){
  t=1/sqrt(var.cov[1,1])
  tt=t*uu%*%mu
  phi=log(1+((tt*pnorm(tt))/dnorm(tt)))
  aa=r*(exp((log(r/var.1))-(r^2/(2*var.1))+(r*(uu%*%mu)/var.1)-phi))
  return(aa)
  }
  integrate(f,0,Inf)
}
integral(u)

我收到以下错误消息: f(x, ...) 中的错误: 暗淡 [产品 10] 与对象 [15] 的长度不匹配 另外:警告信息: 在 r * (uu %*% mu) 中: 较长的对象长度不是较短对象长度的倍数

f(x, ...) 中的错误: 暗淡 [产品 10] 与对象 [15] 的长度不匹配 另外:警告信息: 在 r * (uu %*% mu) 中: 较长的对象长度不是较短对象长度的倍数

【问题讨论】:

    标签: r


    【解决方案1】:

    Integrate 需要矢量化函数f。从嵌套积分函数中提取 f 。使用输入 11:10 测试 f,看看会发生什么。 integrate 试图将向量 rn * 2 矩阵 (uu %*% mu) 相乘,但它不能这样做,因为 r 的长度不一定是 n (或其中的某个倍数)。

    【讨论】:

    • 非常感谢您的回复,但即使我提取了集成函数并尝试获取第一次观察的值,我仍然收到错误消息。我将 cods 修改如下`f=function(r) { q=1/sqrt(var.cov[1,1]) tt=qu[1,]%*%mu phi=log(1+((ttpnorm(tt))/ dnorm(tt))) aa=r*(exp((log(r/var.1))-(r^2/(2*var.1))+(r*(u[1,]%*% mu)/var.1)-phi)) return(aa) } 积分(f,0,Inf)`
    • 我收到错误消息:In (log(r/var.1)) - (r^2/(2 * var.1)) + (r * (u[1, ] %* % ... : 不推荐在向量数组算法中回收长度为 1 的数组。请改用 c() 或 as.vector()。
    • 你可以试试 f(c(1))。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2017-05-16
    • 2020-06-02
    • 2017-12-22
    • 2011-07-20
    相关资源
    最近更新 更多