Search code examples
rmontecarlo

Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix in MetRology uncertMC with 2x2 correlation matrix


I am attempting to learn how to use the MetRology package in R. I have been using the data in Appendix H.2 of the GUM manual as a simple example to attempt Monte Carlo uncertainty propagation including correlation. I have two variables V and I. Therefore I have a 2x2 correlation matrix with the correlation between I,V in the off-diagonal elements. If I supply this matrix to the uncertMC function, I get the error: "Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix". If I do not include the correlation matrix, I do not get the error. Why am I getting the error when correlation is included? The metRology manual has an example with four variables and a 4x4 correlation matrix which works for me. Is there something obvious I'm doing wrong?

Thank you in advance!

library(errors) # for gum H.2 dataset
library(metRology) # for uncertMC

#extract relevant data

meanV  <-  with(GUM.H.2, mean(V))
meanI  <-  with(GUM.H.2, mean(I))

#uncertainties of the mean as per GUM (over sqrt(N))

uV <-  with(GUM.H.2, sd(V)/sqrt(length(V)))
uI <-  with(GUM.H.2, sd(I)/sqrt(length(I)))

# correlation between V and I

corIV  <-  with(GUM.H.2, cor(I,V))

#set up a 2 x 2 correlation matrix

u.cor <-  diag(1,2)

# off-diagonal elements

u.cor[1,2] <- u.cor[2,1] <-  corIV

#set up inputs for uncertMC

# the expression Z = V/I

expr <-  expression(V/I)

x <- list(V= meanV, I= meanI)

u  <-  list(V=uV, I=uI)

u.MC <-  uncertMC(expr = expr, x = x, u = u, cor = u.cor)

#errors with Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix

Solution

  • I was checking traceback & uncertMC function and there is a piece of code to define Sigma:

    Sigma = cov[cor.vars, cor.vars]
    

    but cor.vars is defined as:

    cor.vars <- which(rowSums(cor) > (1 + .Machine$double.eps * 
                nrow(cor)))
    

    the issue is that if you have negative correlations, eventually rowSums(cor) will not meet the condition, so you will get integer(0).

    As you said, the metRology manual has an example with four variables and a 4x4 correlation matrix which works for you, but if you change the sign of correlation you get the same error:

    expr <- expression(a+b*2+c*3+d/2)
    x <- list(a=1, b=3, c=2, d=11)
    u <- lapply(x, function(x) x/10)
    u.cor<-diag(1,4)
    u.cor[3,4]<-u.cor[4,3]<- -0.5 # change sign to negative
    u.formc.MC<-uncertMC(~a+b*2+c*3+d/2, x, u, cor=u.cor, keep.x=TRUE)
    u.formc.MC
    
    # Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix