【问题标题】:Why does the code work when run as a R script but shows error when run in reprex?为什么代码在作为 R 脚本运行时可以工作,但在 reprex 中运行时显示错误?
【发布时间】:2020-06-24 03:01:03
【问题描述】:
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"

我确定我已经使用library(ggplot2) 加载了 ggplot2 包。当我在 R 脚本中运行这两个代码行时,它确实有效,我可以看到查看器中生成的图。但是当我使用 reprex 运行这两个代码行时,它会显示类似上面的错误(我这样做是因为我想使用 reprex 运行它们并将结果粘贴到堆栈溢出以询问有关两个代码行之间的区别的问题) .我想知道为什么它在reprex中显示错误。

【问题讨论】:

    标签: r ggplot2 reprex


    【解决方案1】:

    在提交给reprex的代码行中导入ggplot2怎么样?即,

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

    也许正在发生的事情是提交给 reprex 的代码在其他地方执行,因此您需要在其中导入包。

    【讨论】:

    • 哦,终于。我在这里得到了我的问题。使用 reprex 时,我们不仅要直接复制命令行(这里是 ggplot 函数及其层),还要复制 ggplot 函数所在的库(ggplot2)。我确实在 R 会话开始时运行了 library(ggplot2),但是在使用 reprex 时,我们还必须复制 library()。非常感谢。
    • 是的,reprex 的想法是完全可重现的。您的代码不能依赖于当前 R 会话中加载的任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多