2017-10-05 57 views
0

創建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

回答

0

正如@Marco Sandri指出的那樣,我只需要將包裝函數包裝在print命令中。

print(NicePlot(df))