sem-in-r / seminr

Natural feeling domain-specific language for building structural equation models in R for estimation by covariance-based methods (like LISREL/Lavaan) or partial least squares (like SmartPLS)
58 stars 19 forks source link

Error calculating total indirect effects #309

Closed NicholasDanks closed 1 year ago

NicholasDanks commented 1 year ago

Thank you very much for spotting this bug in my code. Without the help and support of our community, we would not be able to find and test all possible code. I identified the problem. The function for calculating the total_effects had some faulty logic. specifically, the function is as follows:

function(path_coef) {
  output <- path_coef
  paths <- path_coef
  while (sum(paths) > 0) {
    paths <- paths %*% path_coef
    output <- output + paths
  }
  return(output)
}

to calculate total effects, we simply need to multiply the path coefficients matrix with iteself and add the product. This continues until the product of the path coef matrix is equal to zero (no more indirect effects). In my logic I had used a while() statement which said to continue calculating the product of the path coef matrix and adding it up until the paths matrix sums to a non-positive. This makes sense because the product of a number with itself cannot be negative. However I did not consider that the initial starting point could sum to a non-neg. Thus, the function was never executing.

My fix is as followS:

function(path_coef) {
  output <- path_coef
  paths <- path_coef
  while (sum(paths) != 0) {
    paths <- paths %*% path_coef
    output <- output + paths
  }
  return(output)
}

Nevertheless, you have brought this glitch to our attention and I can now deploy the bug-fix in our next version. In the meantime, you can download the bugfix version (temp) using:

devtools::install_github(repo = "https://github.com/sem-in-r/seminr/", ref = "bugfixes_aug_2022")