1

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.

3
  • From MegaFunction return: return(list(plotResult = NicePlot(df), dataResult = df)) Commented Oct 5, 2017 at 13:31
  • 1
    Use print(NicePlot(df)) inside MegaFunction Commented Oct 5, 2017 at 13:33
  • @Marco thanks! That works and is nice and simple. If you want you can enter it as an answer that I will mark as "the answer". Commented Oct 5, 2017 at 14:00

1 Answer 1

1

As @Marco Sandri pointed out, I simply had to wrap the wrapper function in a print command.

print(NicePlot(df))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.