Skip to content

Instantly share code, notes, and snippets.

@strengejacke
Last active May 21, 2022 09:01
Show Gist options
  • Save strengejacke/5ec65e8f752d62ddf67b837cd557e375 to your computer and use it in GitHub Desktop.
Save strengejacke/5ec65e8f752d62ddf67b837cd557e375 to your computer and use it in GitHub Desktop.
Approach of different packages to generate predicted values
library(insight)
library(datawizard)
library(modelbased)
library(ggeffects)
library(emmeans)
library(marginaleffects)
data(efc, package = "ggeffects")
efc <- data_to_factor(efc, select = "c161sex")
model <- lm(neg_c_7 ~ barthtot + c160age * c161sex, data = efc)
# create reference grid
grid <- get_datagrid(model, at = list(c161sex = c("Male", "Female"), c160age = 50))
# ggeffects
ggpredict(model, c("c160age [50]", "c161sex"))
#> # Predicted values of Negative impact with 7 items
#>
#> # c161sex = Male
#>
#> c160age | Predicted | 95% CI
#> ------------------------------------
#> 50 | 11.54 | [11.05, 12.03]
#>
#> # c161sex = Female
#>
#> c160age | Predicted | 95% CI
#> ------------------------------------
#> 50 | 11.87 | [11.59, 12.15]
#>
#> Adjusted for:
#> * barthtot = 64.66
ggpredict(model, "c161sex", condition = c(c160age = 50))
#> # Predicted values of Negative impact with 7 items
#>
#> c161sex | Predicted | 95% CI
#> ------------------------------------
#> Male | 11.54 | [11.05, 12.03]
#> Female | 11.87 | [11.59, 12.15]
#>
#> Adjusted for:
#> * barthtot = 64.66
# marginaleffects
predictions(model, newdata = grid)
#> rowid type predicted std.error conf.low conf.high c160age c161sex
#> 1 1 response 11.53973 0.2487972 11.05141 12.02804 50 Male
#> 2 2 response 11.86866 0.1411197 11.59168 12.14563 50 Female
#> barthtot
#> 1 64.6617
#> 2 64.6617
# modelbased
estimate_expectation(model, grid)
#> Model-based Expectation
#>
#> c160age | c161sex | barthtot | Predicted | SE | 95% CI
#> ----------------------------------------------------------------
#> 50.00 | Male | 64.66 | 11.54 | 0.25 | [11.05, 12.03]
#> 50.00 | Female | 64.66 | 11.87 | 0.14 | [11.59, 12.15]
#>
#> Variable predicted: neg_c_7
#> Predictors modulated: c("Male", "Female"), 50
#> Predictors controlled: barthtot
# emmeans
emmeans(model, "c161sex", at = list(c160age = 50))
#> NOTE: Results may be misleading due to involvement in interactions
#> c161sex emmean SE df lower.CL upper.CL
#> Male 11.5 0.249 867 11.1 12.0
#> Female 11.9 0.141 867 11.6 12.1
#>
#> Confidence level used: 0.95
# insight
get_predicted(model, data = grid) |> as.data.frame()
#> Predicted SE CI_low CI_high
#> 1 11.53973 0.2487972 11.05141 12.02804
#> 2 11.86866 0.1411197 11.59168 12.14563
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment