H A
H A

Reputation: 81

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

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

enter image description here

Upvotes: 0

Views: 2035

Answers (2)

Edward
Edward

Reputation: 19394

On line 9, you have:

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 is created on line 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:

7: xobs <- x[groups==i,]

Does that fix the problem?

Upvotes: 2

In your function, xobs seems to be a vector, you are using xobs[nrow(xobs)] but class vector do not have rows, try:

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

Upvotes: 0

Related Questions