【发布时间】: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