---
title: "simple slopes analysis"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{simple slopes analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
EVAL_DEFAULT <- FALSE
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = EVAL_DEFAULT
)
```

```{r setup}
library(modsem)
```

# Simple Slopes Analysis

Simple slope effects can be plotted using the included `plot_interaction()` function. This function takes a fitted model object and the names of the two variables that are interacting. The function will plot the interaction effect of the two variables, where:

- The x-variable is plotted on the x-axis.
- The y-variable is plotted on the y-axis.
- The z-variable determines at which points the effect of x on y is plotted.
  
The function will also plot the 95% confidence interval for the interaction effect. 
Note that the `vals_z` argument (as well as the values of `x`) are scaled by the
mean and standard deviation of the variables. Unless the `rescale` argument is set to `FALSE`.

Here is a simple example using the double-centering approach:

```{r}
m1 <- "
# Outer Model
  X =~ x1
  X =~ x2 + x3
  Z =~ z1 + z2 + z3
  Y =~ y1 + y2 + y3

# Inner Model
  Y ~ X + Z + X:Z
"
est1 <- modsem(m1, data = oneInt)
plot_interaction(x = "X", z = "Z", y = "Y", vals_z = c(0, 1), model = est1)
```

If you want to see the numerical values of the simple slopes, you can use the `simple_slopes()` function:

```{r}
m1 <- "
# Outer Model
  X =~ x1
  X =~ x2 + x3
  Z =~ z1 + z2 + z3
  Y =~ y1 + y2 + y3

# Inner Model
  Y ~ X + Z + X:Z
"

est1 <- modsem(m1, data = oneInt)
simple_slopes(x = "X", z = "Z", y = "Y", vals_z = c(0, 1), model = est1)
```

The `simple_slopes()` function returns a simple_slopes object, which is a `data.frame`
with some additional attributes. It only has a single method (or technically, a generic function),
`print.simple_slopes()`, which prints the simple slopes in a easy-to-read format. If you want to 
extract the simple slopes as a `data.frame`, you can use the `as.data.frame()` function:


```{r}
m1 <- "
# Outer Model
  X =~ x1
  X =~ x2 + x3
  Z =~ z1 + z2 + z3
  Y =~ y1 + y2 + y3

# Inner Model
  Y ~ X + Z + X:Z
"

est1 <- modsem(m1, data = oneInt)
slopes <- simple_slopes(x = "X", z = "Z", y = "Y", 
                        vals_z = c(0, 1), model = est1)
as.data.frame(slopes)
```


