install.packages('devtools')
library(devtools)
install_github("jslefche/piecewiseSEM")
library(piecewiseSEM)

#### piecewise SEM
library(ape) #Version 3.3
library(caper) # Version 0.5.2
library(nlme) # Version 3.1.122
library(lavaan) # Version 0.5.19
library(plyr)

dataS = read.csv("Additional file 1.Wing length and Longevity Data set.csv")
vars = c("temperature", "larval.diet", "longevity.in.days", "wing.length.in.mm", "censor")
dataS = dataS[, vars]

dataS$temperature<-as.factor(dataS$temperature)
dataS <- rename(dataS, c("larval.diet"="food", "longevity.in.days"="survival", "wing.length.in.mm"="wsize"))
dataS <- rename(dataS, c("temperature"="temp"))
#for plotting ease

# Create component models and store in list
longevity_pSEM_randomList = list(
  
  # Predicting wing length
  wsize = lm(wsize ~ food + temp, data = dataS),
  
  # Predicting longevity
  longevity = lm( survival ~ wsize*food*temp, data = dataS)
  
)

# Run goodness-of-fit tests
sem.fit(longevity_pSEM_randomList, dataS)

# Evaluate path significance using unstandardized coefficients
sem.coefs(longevity_pSEM_randomList, dataS, standardize = "none")

# Obtain standardized regression coefficients
sem.coefs(longevity_pSEM_randomList, dataS, standardize = "scale")

# Explore individual model fits
rsquared(longevity_pSEM_randomList)

# plot (The plot doesn't work well and may not work in latest version. It was done on the website overleaf instead using the LaTex language)
sem.plot(longevity_pSEM_randomList, dataS)

