生成ggplot和函数调用

问题描述:

创建ggplot是一个函数调用的副作用时,我有一个问题,返回的输出:生成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这个工作。

+0

从'MegaFunction'返回:'回报(名单(plotResult = NicePlot(DF),dataResult = DF))' – PoGibas

+1

使用'印刷(NicePlot(DF))''里面MegaFunction' –

+0

@Marco的感谢!这工作,很好,很简单。如果你愿意,你可以把它作为答案,我将标记为“答案”。 – Japhir

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

print(NicePlot(df))