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

dataframematrixr

I'm trying to generate a data frame of simulated values from the student's t distribution using the standard stochastic equation. The function I use is as follows:

matgen<-function(means,chi,covariancematrix)
{
 cols<-ncol(means);
 normals<-mvrnorm(n=500,mu=means,Sigma = covariancematrix);
 invgammas<-rigamma(n=500,alpha=chi/2,beta=chi/2);
 gen<-as.data.frame(matrix(data=NA,ncol=cols,nrow=500));
 i<-1;
 while(i<=500)
 {
   gen[i,]<-t(means)+normals[i,]*sqrt(invgammas[i]);
   i<=i+1;
 }
return(gen);
}

If it's not clear, I'm trying to create an empty data frame, that takes in values in cols number of columns and 500 rows. The values are numeric, of course, and R tells me that in the 9th row:

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

There's an error: 'non-numeric matrix extent'.

I remember using as.data.frame() to convert matrices into data frames in the past, and it worked quite smoothly. Even with numbers. I have been out of touch for a while, though, and can't seem to recollect or find online a solution to this problem. I tried is.numeric(), as.numeric(), 0s instead of NA there, but nothing works.

Best Answer

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

Related Topic