DHARMa icon indicating copy to clipboard operation
DHARMa copied to clipboard

Add support for piecewiseSEM in DHARMa

Open florianhartig opened this issue 4 years ago • 1 comments

I have been thinking about this, see comments in https://github.com/jslefche/piecewiseSEM/issues/197

Perspective for this request: Currently, the package does not allow to simulate from the fitted model, which prevents an easy integration into DHARMa. Support could be added if the package developers implement a simulate function, see here

Interim solution for users that, for some reason, have to urgently use DHARMa with this package: take your fitted model, create a simulate function for this model structure yourself, and then use createDHARMa (see help), this will allow most options of the package to be run. See further comments on support of new packages in here. Note that the vignette has some further comments / examples on creating custom simulation functions and reading them into DHARMa

florianhartig avatar Dec 17 '19 10:12 florianhartig

Here a piece of code that calculates DHARMa residuals for a fitted psem object

library(piecewiseSEM)

mod = psem(
  lm(rich ~ distance + elev + abiotic + age + hetero + firesev + cover, data =  keeley),
  lm(firesev ~ elev + age + cover, data =  keeley), 
  lm(cover ~ age + elev + abiotic, data =  keeley)
)

summary(mod)
plot(mod)


library(DHARMa)
residuals2 <- function(fittedPSEM, type = "DHARMa"){
  if(type == "standard"){
    return(residuals(fittedPSEM))
  }
  if(type == "DHARMa"){
    sim = list()
    res = list()
    for(i in 1:(length(fittedPSEM) - 1)){
      sim[[i]] <- simulateResiduals(fittedPSEM[[i]])
      res[[i]] = sim[[i]]$scaledResiduals
    }
    res = matrix(unlist(res),ncol=length(res),byrow=F)
    return(list(residuals = res, DHARMaSimulations = sim))
  }
}

res = residuals2(mod)
res$residuals
# plots and tests for model 1
plot(res$DHARMaSimulations[[1]])
testResiduals(res$DHARMaSimulations[[1]])
# in principle, it would be possible to plot residuals also against a particular path, or test for homogeneity along this path

florianhartig avatar Dec 17 '19 12:12 florianhartig