How to counter the ‘non-numeric matrix extent’ error in R?

As Roland pointed out, one problem is, that col doesn’t seem to be numeric. Please check if means is a dataframe or matrix, e.g. str(means). If it is, your code should not result in the error: ‘non-numeric matrix extent’.

You also have some other issues in your code. I created a simplified example and pointed out the bugs I found as comments in the code:

library(MASS)
library(LearnBayes)

means <- cbind(c(1,2,3),c(4,5,6))
chi <- 10

matgen<-function(means,chi,covariancematrix)
{
  cols <- ncol(means) # if means is a dataframe or matrix, this should work

  normals <- rnorm(n=20,mean=100,sd=10) # changed example for simplification
  # normals<-mvrnorm(n=20,mu=means,Sigma = covariancematrix) 
  # input to mu of mvrnorm should be a vector, see ?mvrnorm; but this means that ncol(means) is always 1 !?

  invgammas<-rigamma(n=20,a=chi/2,b=chi/2) # changed alpha= to a and beta= to b

  gen<-as.data.frame(matrix(data=NA,ncol=cols,nrow=20))

  i<-1
  while(i<=20)
  {
    gen[i,]<-t(means)+normals[i]*sqrt(invgammas[i]) # changed normals[i,] to normals [i], because it is a vector
    i<-i+1 # changed <= to <- 
  }
  return(gen)
}

matgen(means,chi,covariancematrix)

I hope this helps. P.S. You don’t need “;” at the end of every line in R

Leave a Comment