[英]Why do I keep getting the error "Argument of Length 0"
I am trying to create a function that has an addition and subtraction of vectors.我正在尝试创建一个具有向量加法和减法的函数。 So, I did the following所以,我做了以下
Qhat <- function(x, groups,I,n,H){
Q4 <- array(0,dim=c(p,I))
p = dim(x)[2]
I=length(unique(groups));
for (i in 1:I){
for (j in 1:n[i]){
xobs<-x[groups==i]
n[i]<- length(xobs)
Q1 <- 1/((n[i]*(n[i]-1))*det(H^(1/2)))
sub <- t(sapply(1:nrow(xobs), function(x) if (x == 1) { xobs[x, ] - xobs[nrow(xobs), ] } else {xobs[x, ] - xobs[x-1, ]}))
add <- t(sapply(1:nrow(xobs), function(x) if (x == 1) { xobs[x, ] + xobs[nrow(xobs), ] } else {xobs[x, ] + xobs[x-1, ]}))
Q2 <- 1/2*add%*%(dmvnorm((sub)%*%(solve(H^(1/2)))))
Q3 <- matrix(c(sum(Q2[,1]), sum(Q2[,2])), nrow =1, ncol=p)
Q4 <- t(Q1[i]*Q3[i])
}
}
return (Q4)
}
where the data I use is我使用的数据在哪里
H <- n[1]^(-1/(p+4))*solve(sigma^(1/2))
p <- 2
n<-c(20,20,20)
mu1=rep(1,p)
mu2=rep(1,p)
mu3=rep(1,p)
sigma <- matrix(c(1.0, 0,
0, 1.0), nrow = 2)
groups<-rep(1:3, n)
x1=mvrnorm(n[1], mu1,sigma)
x2=mvrnorm(n[2], mu2,sigma)
x3=mvrnorm(n[3], mu3,sigma)
x=rbind(x1,x2,x3)
However, I keep getting the error但是,我不断收到错误
Error in 1:nrow(xobs) : argument of length 0 1:nrow(xobs) 中的错误:长度为 0 的参数
I don't understand why I have a problem in the function, although when I try doing the same thing with numbers outside of the function it works just fine.我不明白为什么我在函数中遇到问题,尽管当我尝试对函数外的数字做同样的事情时,它工作得很好。
Edit:编辑:
I am mainly trying to create a function that takes each vector (row)(2-dimensional) in the data and subtract/add it from/to the rest of the vectors for each group.我主要是尝试创建一个函数,该函数采用数据中的每个向量(行)(二维),并将其从/添加到每个组的其余向量中。 So in this example I have 3 groups and I want to to do something that would calculate the following function所以在这个例子中,我有 3 个组,我想做一些可以计算以下函数的事情
On line 9, you have:在第 9 行,您有:
9: sub <- t(sapply(1:nrow(xobs), function(x) if (x == 1) {
xobs[x, ] - xobs[nrow(xobs), ] } else {xobs[x, ] - xobs[x-1, ]}))
But xobs
is a vector with no dimension, so 1:nrow(xobs)
fails.但是xobs
是一个没有维度的向量,所以1:nrow(xobs)
失败。
xobs
is created on line 7: xobs
在第 7 行创建:
7: xobs <- x[groups==i]
If you want this to be a matrix-like object, similar to x
, then you need to add a comma:如果你希望它是一个类似矩阵的对象,类似于x
,那么你需要添加一个逗号:
7: xobs <- x[groups==i,]
Does that fix the problem?这能解决问题吗?
In your function, xobs
seems to be a vector, you are using xobs[nrow(xobs)]
but class vector do not have rows, try:在您的函数中, xobs
似乎是一个向量,您使用的是xobs[nrow(xobs)]
但类向量没有行,请尝试:
nrow(1:10) # NULL
x[nrow(x)] # yields Error in 1:10[nrow(1:10)] : argument of length 0
# but
nrow(as.matrix(1:10))
# [1] 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.