使用match检查字符和函数类型对象

时间:2019-05-30 20:59:09

标签: r ggplot2 user-defined-functions

我正在编写一个自定义函数,该函数绘制一条平滑线并仅在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创建

1 个答案:

答案 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)
}