如何在自定义 ggplot 函数中调用 facet_wrap()?

How to call facet_wrap() inside custom ggplot function?

我正在尝试创建一个函数来将包 rmcorr 的输出与 ggplot 相结合。 rmcorr 的文档包含有关如何使用 ggplot 呈现输出的示例。我无法让分组变量为我的自定义函数工作(下面的第 3 段代码)。

这是代码和下图,没有为分面分组变量,一切看起来都很好:

rmcorr_fun_2 <- function(p,m1,m2) {
  my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
  print(my.rmc)
  p <- sym(p)
  m1 <- sym(m1)
  m2 <- sym(m2)
  #grp <- sym(grp)
  print(ggplot(data = mtcars, aes(x = !!m1, y = !!m2, group = factor(!!p), color = factor(!!p)))+
          geom_point(aes(colour = factor(!!p))) +
          geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1))
          #facet_wrap(.~(!!grp)))
}

使用上面相同的代码,但添加 grp 变量并删除散列以进行分组:

rmcorr_fun_2 <- function(p,m1,m2,grp) {
  my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
  print(my.rmc)
  p <- sym(p)
  m1 <- sym(m1)
  m2 <- sym(m2)
  grp <- sym(grp)
  print(ggplot(data = mtcars, aes(x = !!m1, y = !!m2, group = factor(!!p), color = factor(!!p)))+
          geom_point(aes(colour = factor(!!p))) +
          geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1)+
          facet_wrap(.~(!!grp)))
}

出现以下错误:

Error in sym(grp) : argument "grp" is missing, with no default
In addition: Warning message:
In rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars) :
  'p' coerced into a factor
Called from: is_symbol(x)

您必须将分面变量包装在 vars().

中,而不是公式符号

此外,如果您将列名作为字符串传递,您可以简单地使用 rlang 中的 .data 代词而不是 sym + !!

library(ggplot2)
library(rmcorr)

rmcorr_fun_2 <- function(p, m1, m2, grp) {
  my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
  print(my.rmc)
  ggplot(data = mtcars, aes(x = .data[[m1]], y = .data[[m2]], group = factor(.data[[p]]), color = factor(.data[[p]]))) +
    geom_point(aes(colour = factor(.data[[p]]))) +
    geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1) +
    facet_wrap(vars(.data[[grp]]))
}

rmcorr_fun_2("cyl", "hp", "disp", "cyl")