R边距:估计样条模型中的边际效应

时间:2020-06-08 21:55:42

标签: r

我想估算一个模型的边际效应,在该模型中将自变量包括为样条曲线。我在R中使用了margins命令来对二次模型执行相同的操作,但是当使用splines包中的函数(例如bs)时,这些命令会失败。这是MWE:

library(tidyverse)
library(margins)
library(splines)

# Create fake data where y is a non-linear function of X ---
N <- 10000

data <- tibble(x = runif(N, 0, 30)) %>%
    mutate(y = 3 + 2*sin(x/5) + rnorm(N))

# Estimate  marginal effects with quadratic and spline models ----

fit_quad <- lm(y ~ x + I(x^2), data = data)
fit_spl <- lm(y ~ x + I(bs(x, knots = c(10,20))), data = data)

# Estimate marginal effects at different values
summary(margins(fit_quad, at = list(x = c(5, 10, 15, 20))))
summary(margins(fit_spl, at = list(x = c(5, 10, 15, 20))))
# Error in bs(x, knots = c(10, 20)) : could not find function "bs"

这可能是一个很高的要求。 “原始” Stata margins命令也不支持样条曲线。但是,似乎还有另一个Stata软件包(marginscontplot)使之成为可能,所以也许R中有一些等效的东西?

0 个答案:

没有答案
相关问题