[英]R: Create a User-defined Function that Plots data and then Exports the plot
Simple objective: I'm trying to create a user-defined fn ( udf
) that will allow me to combine a few lines of code so it's condensed and easier to read.简单目标:我正在尝试创建一个用户定义的 fn ( udf
),它允许我组合几行代码,使其更简洁udf
易于阅读。
Let's take an easy example.让我们举一个简单的例子。 In one fn, I'd like to plot some data and then export the plot using the tiff
fn (or any similar fn: png
, jpeg
, ...).在一个 fn 中,我想绘制一些数据,然后使用tiff
fn(或任何类似的 fn: png
, jpeg
,...)导出该图。 However, I want to be able to use any plot function of my choice , so I thought passing a code block (let's call it ' plotcode ') to a fn call would work just fine.但是,我希望能够使用我选择的任何绘图函数,所以我认为将代码块(我们称之为“ plotcode ”)传递给 fn 调用会工作得很好。 Something along the lines of:类似的东西:
udf <- function(plotcode, title){
plotcode
tiff(filename=title)
plotcode
dev.off()
}
The ultimate goal being to turn 4 lines of code into 1, ie:最终目标是将4行代码变成1行,即:
plot(dat) # ====> udf(plotcode = plot(dat), title = "plot.tiff")
tiff("myplot.tiff")
plot(dat)
dev.off()
Unfortunately, it only plots the data and does not export it to a file.不幸的是,它只绘制数据而不会将其导出到文件中。 From what I understand, it's because I'm opening a graphics device when I use the export function, so it doesn't recognize the plotcode anymore?据我了解,这是因为我在使用导出功能时打开了图形设备,所以它不再识别绘图代码?
I did find one alternative solution, the do.call
fn, but it makes you separate the plotcode into two pieces: (1)fn name & (2)arguments.我确实找到了一种替代解决方案, do.call
fn,但它使您将plotcode分成两部分:(1)fn name & (2)arguments。 I'm hoping to keep the plotcode together so it's easer to copy/paste later.我希望将plotcode保持在一起,以便以后复制/粘贴更容易。
Maybe there's even another option I'm not thinking of?也许还有我没有想到的另一种选择?
Following code lets you pass code that creates a plot, create the plot and save the plot.以下代码可让您传递创建绘图、创建绘图和保存绘图的代码。
library(tidyverse)
udf <- function(plotcode, title){
eval(plotcode)
ggsave(title)
}
udf('qplot(mtcars$mpg)', 'plot.jpg')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.