I've simulated an example in which a treatment is randomly allocated to a group of people and then some continuous measure is observed.
The treatment group sees a spike in their response and then a sharp decline. A plot of the conditional mean is show below. The control group has a flat response.
The sum of difference between treatment and control over days, plus its standard error, is of interest. I was hoping I could do this with marginaleffects
From the functional form, sum of differences should be around 3.2. However, when I use avg_comparisons
I get something closer to 0.
Here is a minimal working example
library(nimble)
#> nimble version 1.0.1 is loaded.
#> For more information on NIMBLE and a User Manual,
#> please visit https://R-nimble.org.
#>
#> Note for advanced users who have written their own MCMC samplers:
#> As of version 0.13.0, NIMBLE's protocol for handling posterior
#> predictive nodes has changed in a way that could affect user-defined
#> samplers in some situations. Please see Section 15.5.1 of the User Manual.
#>
#> Attaching package: 'nimble'
#> The following object is masked from 'package:stats':
#>
#> simulate
library(tidyverse)
library(marginaleffects)
set.seed(0)
mu <- \(x) 10*ddexp(x, location=7, scale=1) - 7*ddexp(x, location=8, scale=1)
d <- crossing(
day = 1:14,
trt = 0:1,
ix = 1:100
) %>%
mutate(
y = 10 + mu(day)*trt + rnorm(n(), 0, 1)
)
fit <- lm(y ~ factor(day)*trt, data=d)
# This gives me something close to what I want
avg_comparisons(fit,
newdata = datagrid(by = c('trt','day')),
variables = 'trt',
by='day')$estimate %>%
sum
#> [1] 3.469189
# This does not
avg_comparisons(fit,
newdata = datagrid(by = c('trt','day')),
variables = 'trt')
#>
#> Term Contrast Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
#> trt 1 - 0 0.248 0.0379 6.53 <0.001 33.9 0.173 0.322
#>
#> Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high
#> Type: response
Created on 2023-10-27 with reprex v2.0.2
How can I estimate the effect I'm interested in using marginaleffects
?
I’m not sure exactly what you mean by
But there’s a good chance you can get what you want by specifying a custom function in the
comparison
argument of thecomparisons()
function. Here’s an example where I compute the sum of differences between treatment and control for each day: