1
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy))
#> Error in ggplot(data = mpg): could not find function "ggplot"

ggplot(mpg, aes(x=displ,y=hwy))+geom_point()
#> Error in ggplot(mpg, aes(x = displ, y = hwy)): could not find function "ggplot"

I make sure I've already loaded the ggplot2 package using library(ggplot2). When I run these two code lines in R script it does work and I can see the plot generated in viewer. But when I use reprex to run these two code lines it shows error like above (I do this because I wanna use reprex to run them and paste the results to stack overflow to ask a question about what the difference between the two code lines is). I wanna know why it shows error in reprex.

Uwe
  • 34,565
  • 10
  • 75
  • 109
Chris
  • 77
  • 9

1 Answers1

1

How about you import ggplot2 in the line of the code submitted to the reprex? I.e.,

library(ggplot2); ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy))

Perhaps what is happening is that the code submitted to the reprex is executed somewhere else and thus you need to import packages within it.

Kota Mori
  • 4,348
  • 15
  • 21
  • 1
    Oh finally. I got what was my problem here. When using reprex, we have to duplicate not only the command lines directly (here it is the ggplot function and its layers), but also the library(ggplot2) where the ggplot function originates. I indeed run library(ggplot2) at the beginning of the R session, but when using reprex we have to duplicate the library() also. Thank you so much. – Chris Mar 12 '20 at 05:39
  • yes, the idea of a reprex is to be fully reproducible. Your code cannot depend on anything loaded in your current R session. – Benjamin Schwetz Mar 12 '20 at 08:21