用R写函数导出PDF图,但PDF损坏

Using R to write a function to export a PDF graph, but PDFs are corrupted

我已经编写了这个函数来在 R 中导出图形。当我 运行 这个函数创建了 pdf 文件,但是它们已损坏并且无法打开(或者当我导出 png 文件时文件为空)。当我 运行 单独的代码行时,它们不作为函数的一部分工作。

求助!!我认为这一定与在函数中制作表格或图表有关,(我必须做类似 return 和 graphs/data 框架的事情吗?)但我不知道是什么!

    graphFunction <- function(fileName){

pdfTitle <- paste(fileName, "_graph", ".pdf", sep = "")

File <- read.csv(fileName, quote = "")
ByPopAge<- ddply(File, .(age), summarise, # need to discount trials where no feeding obs and eve
        NCols = length(!is.na(colony_ID)),
        TotNumInd = sum(num.indvs)
)

pdf(pdfTitle, width =10, height =10)

ggplot(data = ByPopAge, aes(x = age, y = TotNumInd)) + geom_line() + geom_point()   
ggplot(data = ByPopAge, aes(x = age, y = NCols)) + geom_line() + geom_point()

dev.off() }

谢谢!

尝试做:

print(ggplot(...))

用印刷品包装它应该可以使用。