【问题标题】:Generate ggplot and return output from function call生成 ggplot 并从函数调用返回输出
【发布时间】:2017-10-05 13:27:13
【问题描述】:

我在创建 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 时我可以做到(如预期的那样)。这可能与调用函数的环境有关,但我无法弄清楚。有任何想法吗?在基础 R 中,这确实有效。

【问题讨论】:

  • 来自MegaFunction 返回:return(list(plotResult = NicePlot(df), dataResult = df))
  • print(NicePlot(df)) 内使用MegaFunction
  • @Marco 谢谢!这很有效,而且很简单。如果你愿意,你可以输入它作为答案,我将标记为“答案”。

标签: r function ggplot2 environment


【解决方案1】:

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

print(NicePlot(df))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 2020-09-10
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多