我正在编写一个自定义函数,该函数绘制一条平滑线并仅在geom_smooth
参数均为线性(即method = "lm"
和formula = y ~ x
)时将字幕显示为“线性模型”。这涉及检查用户为这两个参数输入的内容。检查输入的复杂方面是,method
参数可以作为字符("lm"
)或作为函数(MASS::rlm
)输入,这就是函数失败的地方。 / p>
如何使它正常工作?
这里是reprex
:
# for reproducibility
set.seed(123)
library(tidyverse)
library(mgcv)
# defining a function to plot smooth line
scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
if (as.character(deparse(formula)) != "y ~ x" ||
!any(method %in% c("lm", stats::lm))) {
subtitle <- "non-linear model"
} else {
subtitle <- "linear model"
}
# creating the plot
ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
geom_smooth(formula = formula, method = method) +
labs(subtitle = subtitle)
}
# different `formula` (works)
scatter_lm(mtcars, wt, mpg, y ~ log(x))
# `method` entered as a character (works)
scatter_lm(mtcars, wt, mpg, y ~ x, "gam")
# `method` entered as a function (doesn't work)
scatter_lm(mtcars, wt, mpg, y ~ x, MASS::rlm)
#> Error in match(x, table, nomatch = 0L): 'match' requires vector arguments
由reprex package(v0.3.0)于2019-05-30创建
答案 0 :(得分:4)
此解决方案有些复杂,但是可以起作用:
scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
a <- paste(deparse(method), collapse = "")
if (as.character(deparse(formula)) != "y ~ x" ||
if (class(method) == "function") {
a != paste(deparse(lm), collapse = "")
} else method != "lm") {
subtitle <- "non-linear model"
} else {
subtitle <- "linear model"
}
#creating the plot
ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
geom_smooth(formula = formula, method = method) +
labs(subtitle = subtitle)
}