【问题标题】:R Code error in matrix: 'dimnames' must be a list矩阵中的 R 代码错误:“dimnames”必须是列表
【发布时间】:2017-02-28 04:16:39
【问题描述】:

我目前正在使用蒙特卡罗方法here。 尽管代码(有一些小的修改)适用于我的 2x2 或 3x3 矩阵,但我的 4x4 矩阵不断收到以下错误代码:

矩阵错误(c(0.0461705, 0, 0, 0, 0, 0.0028639, 0, 0, 0, 0, 0.0740766, : 'dimnames' 必须是一个列表

我做错了什么以及如何解决此错误消息?

################################################
# This code can be edited in this window and   #
# submitted to Rweb, or for faster performance #
# and a nicer looking histogram, submit        #
# directly to R.                               #
################################################
require(MASS)
a=1.1727132                       
b=0.2171818
c=1.3666784
d=0.1850852
rep=20000
conf=95
pest=c(a,b,c,d)
acov <- matrix(c(
0.0461705, 0, 0, 0,
0, 0.0028639, 0, 0,
0, 0, 0.0740766, 0,
0, 0, 0, 0.0013694
),4,4,4,4)
mcmc <- mvrnorm(rep,pest,acov,empirical=FALSE)
abcd <- mcmc[,1]*mcmc[,2]*mcmc[,3]*mcmc[,4]
low=(1-conf/100)/2
upp=((1-conf/100)/2)+(conf/100)
LL=quantile(abcd,low)
UL=quantile(abcd,upp)
LL4=format(LL,digits=4)
UL4=format(UL,digits=4)
################################################
# The number of columns in the histogram can   #
# be changed by replacing 'FD' below with      #
# an integer value.                            #
################################################
hist(abcd,breaks='FD',col='skyblue',xlab=paste(conf,'% Confidence Interval ','LL',LL4,'  UL',UL4),
main='Distribution of Indirect Effect')

谢谢!

【问题讨论】:

  • matrix 的参数太多:应该是 matrix(c(...), 4,4)

标签: r statistics


【解决方案1】:

正如@Remko 所说,请正确指定参数。 R矩阵可以创建为:

acov <- matrix(c(
0.0461705, 0, 0, 0,
0, 0.0028639, 0, 0,
0, 0, 0.0740766, 0,
0, 0, 0, 0.0013694
),nrow = 4, ncol = 4, byrow = T,dimnames = list(c("r","o","w","s"),c("c","o","l","s")))

如果您希望数据按列排列,您可以设置 byrow = F。 rownames 和 colnames 向量的长度必须分别与行数和列数匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2019-01-08
    • 2017-03-19
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多