我尝试使用 margins
包来获取简单线性模型的边际效应,但它返回错误:
Error in eval(model[["call"]][["data"]], env) : object '.' not found
此数据可用于重现问题:
forty_rows <- structure(list(wk_dist_eff_nov16 = structure(c(18, -24, -35,
-30, 18, 18, 4, -56, -41, 31, 18, -20, 36, 18, -15, 18, 35, 18,
18, -58, -52, -21, -47, 19, 18, 23, -38, 4, -50, -63, 31, -2,
-27, 2, 18, 18, -8, -12, 14, 19), class = "difftime", units = "days"),
election_2016_11 = c(NA, NA, "0", NA, "0", "0", "1", NA,
NA, "0", "0", NA, "1", "0", "0", "0", "1", "0", "0", NA,
NA, "0", "0", "0", "1", "1", "1", "1", NA, NA, "0", NA, "0",
NA, "1", "0", NA, NA, "0", "1")), class = "data.frame", row.names = c(NA,
-40L))
library(tidyverse)
model <- forty_rows %>%
filter(!is.na(election_2016_11),
wk_dist_eff_nov16 %in% -36:0) %>%
lm(as.numeric(election_2016_11) ~ as.factor(wk_dist_eff_nov16), data = .)
这会返回一些无意义的值,但这只是我创建一个小型可重现示例的人为因素(从 > 500k 的 df 中仅采样 40 行)。然后我可以在 model
对象上调用 tidy()
没有问题,但 margins()
返回错误:
tidy(model)
# A tibble: 4 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0 NaN NaN NaN
2 as.factor(wk_dist_eff_nov16)-27 0 NaN NaN NaN
3 as.factor(wk_dist_eff_nov16)-21 0 NaN NaN NaN
4 as.factor(wk_dist_eff_nov16)-15 0 NaN NaN NaN
library(margins)
margins(model)
Error in eval(model[["call"]][["data"]], env) : object '.' not found
有谁知道这里出了什么问题吗?我该如何解决它?
最佳答案
margins
内部使用一些 find_data(model,parent.frame())
内容来查找数据,并且由于管道的原因只找到 .
.
您可以尝试显式定义可在 model$model
中找到的数据。
library(dplyr)
model <- mtcars %>%
mutate(foo='bar') %>%
lm(mpg ~ hp, data=.)
margins(model)
# Error in eval(model[["call"]][["data"]], env) : object '.' not found
margins(model, data=model$model)
# hp
# -0.06823
适用于mtcars
,但不适用于您的示例数据。
关于r - margins 包返回错误 eval 中的错误(model[ ["call"]][ ["data"]], env) : object '.' not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71099732/