假设我有 2 个源文件,第一个名为 example1.r,第二个名为 example2.r(如下所示).
Let's assume I have 2 source files, the first one named example1.r and the second one example2.r (given below).
example1.r
plot(1:10,1:10)example2.r
qplot(1:10,1:10)当我获取 example1.r 时,会绘制图表.但是,当我获取 example2.r 时,它不会.这里的解决方案是什么?
When I source example1.r, the graph is drawn. It does not, however, when I source example2.r. What is the solution here?
(example2.r中的qplot是ggplot2的函数)
(qplot in example2.r is ggplot2's function)
推荐答案更新:
- .R 文件: source 的选项 print.eval=TRUE 将导致评估结果的打印行为,如交互式命令行.
- .R files: source's option print.eval=TRUE will lead to printing behaviour of the evaluation result like in the interactive command line.
source("Script.R", print.eval=TRUE)
- .Rnw 文件: knitr 默认模拟交互式命令行 wrt 的行为.打印ing.请注意,knitr 也可以指定为 R 包小插图的 Sweaving 引擎.
- .Rnw files: knitr by default emulates the behaviour of the interactive command line wrt. printing. Note that knitr can be specified as Sweaving engine also for R package vignettes.
这是我的原始答案.但请注意,恕我直言,这种解决方法现在已经完全过时了(而且它总是只适用于一个小懒惰的利基市场).
这是著名的 FAQ 7.22:为什么格子/格子图形不起作用?.
对于像 ggplot2 或 lattice 这样的网格图形,您需要打印图形对象才能实际绘制它.
For grid graphics like ggplot2 or lattice, you need to print the graphics object in order to actually draw it.
在命令行上以交互方式自动完成.其他任何地方(要获取的内部文件、循环、函数、Sweave 块)都需要显式打印.
Interactively on the command line this is done automatically. Everywhere else (inside files to be sourced, loops, functions, Sweave chunks) you need to print it explicitly.
print (qplot (1 : 10, 1 : 10))或者,您可以重新定义 qplot 来进行打印:
Alternatively, you can redefine qplot to do the printing:
qplot <- function (x, y = NULL, z = NULL, ...) { p <- ggplot2::qplot (x = x, y = y, z = z, ...) print (p) }(这会将轴标签更改为 x 和 y).
(this changes the axis labels to x and y).
我在小插曲中使用这种方法,我希望在其中编写代码的方式与用户在交互式会话中键入的完全一样.
I use this approach in vignettes where I want to write code exactly as a user in an interactive session would type it.
更多推荐
ggplot 的 qplot 在采购时不执行
发布评论