从函数调用生成 ggplot 和 return 输出

Generate ggplot and return output from function call

我在创建 ggplot 作为函数调用的副作用时遇到问题:

MWE:

library(ggplot2)

dat <- data.frame(x = 1:10,
  y = rnorm(10, 11:20),
  id = sample(letters[1:3], 10, replace= T))

MegaFunction <- function(df) {
  # do something to the data
  df$y <- df$y - 10
  # plot it
  NicePlot(df)
  # return output
  return(df)
}

NicePlot <- function(x) {
  ggplot(x, aes(x = x, y = y, col = id)) +
    geom_point()
}

MegaFunction(dat)  # returns values, but doesn't plot
out <- MegaFunction(dat)  # returns values as out
NicePlot(out)      # plots values successfully

所以问题是我无法使用 MegaFunction 创建绘图,但是当我在 MegaFunction 的输出上调用 NicePlot 时我可以创建绘图(如预期的那样)。这可能与调用函数的环境有关,但我无法弄清楚。有任何想法吗?在 base R 中这确实有效。

正如@Marco Sandri 指出的那样,我只需要将包装函数包装在 print 命令中。

print(NicePlot(df))