简体   繁体   中英

How to print pdf from a function

I have a series of tables and graphs that are produced from a list in R. I would like to create a pdf for each iteration of the list. I have tried simply using pdf() within the function but I get the error that too many graphic devices are open. How can I do this (and name the files according to the list element name?

So far I have tried:

ReportPDF<-function(x){
pdf(paste(name(x),"~\\Myfile.pdf")
tb<-table(x$acolumn)
print(fb)
}

lapply(mylist,ReportPDF)

I cant quite work out how to attach the name of the list element to the filename and I'm not even sure this is the best way to create a pdf from lapply

Can you clean some of this up? Please give a more specific example of the object you're passing to ReportPDF(), I would expect a plot object, rather than what appears to be a data frame that you are selecting a column from. The function example has some errors too, did you mean this?

ReportPDF<-function(x){
pdf(paste(names(x),"Myfile.pdf"))
tb<-table(x$acolumn)
print(tb)
dev.off()
}

lapply(mylist,ReportPDF)

I believe I've done something similar before and can update this answer when I get the other information.

Here's an update making some assumptions about your objects. It uses a for loop as lmo suggests, but I think a more elegant method must exist. I'm using the for loop because lapply passes the object within each element of the list, with no reference to name of the element in the list -- which is what you need to name the files individually. Note the difference between calling mylist[i] and mylist[[i]] , which is part of what's breaking the code in your example. In your code, names(x) will get the names of the columns within x, rather than the name of x as it is inside of mylist, which is what you want.

x <- data.frame(acolumn = rnorm(10))
q<- data.frame(acolumn = rnorm(10))

mylist <- list(a = x,b = q)


for(i in seq_along(mylist) ){
  filename <- paste(names(mylist[i]),'-myFile.pdf', sep = "")
  pdf(filename)
  plot(myList[[i]]$acolumn)
  dev.off()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM