I've got a problem when creating a ggplot as a side-effect of a function call:
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
So the problem is that I can not create the plots using MegaFunction, but I can do it when I call NicePlot on the output of MegaFunction (as expected). This probably has something to do with the environment the function is called from, but I cannot figure it out. Any ideas? In base R this does work.
MegaFunctionreturn:return(list(plotResult = NicePlot(df), dataResult = df))print(NicePlot(df))insideMegaFunction