从 `lm()` 恢复原始变量名

teu*_*and 3 r ggplot2 lm

我对在 ggplot2 中自动绘制模型感兴趣。根据对 ggplot2 问题跟踪器的讨论,我相信像下面这样的包装器应该可以工作。

geom_predict <- function(model, fixed_terms = list(), ...) {
  force(model)
  force(fixed_terms)
  fun <- function(x) { 
    terms <- c(list(x = x), fixed_terms)
    predict(model, newdata = do.call(data.frame, terms))
  }
  geom_function(fun = fun, ...)
}
Run Code Online (Sandbox Code Playgroud)

如果模型的形式为 ,则此方法非常有效y ~ x

library(ggplot2)
library(tibble)

set.seed(0)
df <- tibble(
  x = runif(20, max = 10),
  y = 5 + 2 * x + 0.5 * x^2 + rnorm(20)
)

fit <- lm(y ~ poly(x, 2), data = df)

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_predict(fit)
Run Code Online (Sandbox Code Playgroud)

但是,如果模型的形式为 ,它就会崩溃some_name ~ other_name

library(ggplot2)
library(tibble)

set.seed(0)
df <- tibble(
  x = runif(20, max = 10),
  y = 5 + 2 * x + 0.5 * x^2 + rnorm(20)
)

fit <- lm(y ~ poly(x, 2), data = df)

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_predict(fit)
Run Code Online (Sandbox Code Playgroud)

reprex 包(v1.0.0)于 2021-07-15 创建

我并不完全熟悉 R 中模型的结构,但我想从模型中提取术语,就像它们在输入数据中一样。该terms()函数不符合要求,因为我只能提取poly(temperature, 2). 我想我需要一种方法来做到这一点:

# Nevermind whether the model makes sense
fit <- lm(pressure ~ poly(temperature, 2), data = pressure)

ggplot(pressure, aes(temperature, pressure)) +
  geom_point() +
  geom_predict(fit)
#> Warning: Computation failed in `stat_function()`:
#> object 'temperature' not found
Run Code Online (Sandbox Code Playgroud)

然后,我可以在将数据提供给函数之前使用它来重命名术语predict()。有任何想法吗?

Rol*_*and 5

您需要从模型中提取 x 变量的名称:

geom_predict <- function(model, fixed_terms = list(), ...) {
  force(model)
  force(fixed_terms)
  vars <- all.vars(model$call$formula)
  stopifnot("Only models with one predictor possible" = length(vars) == 2L)
  xname <- vars[2]
  fun <- function(x) { 
    terms <- c(setNames(list(x), xname), fixed_terms)
    predict(model, newdata = do.call(data.frame, terms))
  }
  geom_function(fun = fun, ...)
}

fit <- lm(pressure ~ poly(temperature, 2), data = pressure)

ggplot(pressure, aes(temperature, pressure)) +
  geom_point() +
  geom_predict(fit)
Run Code Online (Sandbox Code Playgroud)

结果图