DJ-AFC
DJ-AFC

Reputation: 569

Create and output multiple plots from list

I am attempting to create and output as pdfs a list of 64 items. My data takes the form:

QQJAN     List of 64

file1: List of 2
..$x: num [1:161] 96.7 96.8 97.5 ...
..$y: num [1:161] 9.3 10.3 17.3 ...
..................................................................
file64: List of 2
..$x: num [1:161] 42.6 59.9 70.4 ...
..$y: num [1:161] 9.3 10.3 17.3 ...

I can do this for any single item in the list using:

plot(QQJAN$file1)

and can then output these files to my working directory as pdfs, but how can all 64 files in the list be plotted and outputted with their names, i.e. file1.pdf, file 2.pdf etc.

Can the lapply function be used here?

A reproducible example:

QQJAN$file1$x=c(1,2,3,4)
QQJAN$file1$y=c(2,4,5,6)

QQJAN$file2$x=c(2,2,3,5)
QQJAN$file2$y=c(2,4,5,6)

Upvotes: 1

Views: 48

Answers (2)

akrun
akrun

Reputation: 886938

We can use lapply to loop over the names of the list elements, create the pdf file by pasteing the individual names with .pdf, subset the list (QQJAN[[x]]), plot.

 invisible(lapply(names(QQJAN), function(x) {
         pdf(paste0(x, '.pdf'))
          plot(QQJAN[[x]])
         dev.off()}))

data

QQJAN <- structure(list(file1 = structure(list(x = c(6L, 5L, 15L, 11L, 
14L, 19L, 6L, 16L, 17L, 6L, 13L, 8L, 14L, 14L, 7L, 19L, 4L, 1L, 
11L, 3L, 2L, 12L, 15L, 3L, 5L, 14L, 2L, 12L, 13L, 1L, 7L, 5L, 
8L, 3L, 19L, 5L, 15L, 13L, 14L, 20L), y = c(29L, 23L, 17L, 14L, 
3L, 5L, 24L, 22L, 16L, 21L, 28L, 52L, 28L, 43L, 33L, 60L, 28L, 
18L, 11L, 9L, 30L, 15L, 17L, 8L, 44L, 19L, 57L, 59L, 45L, 30L, 
9L, 13L, 1L, 60L, 39L, 21L, 35L, 50L, 3L, 44L)), .Names = c("x", 
"y")), file2 = structure(list(x = c(11L, 3L, 11L, 5L, 8L, 7L, 
6L, 18L, 8L, 17L, 7L, 15L, 19L, 3L, 10L, 12L, 13L, 2L, 9L, 10L, 
15L, 13L, 3L, 6L, 16L, 1L, 20L, 5L, 9L, 4L, 12L, 1L, 6L, 13L, 
18L, 7L, 18L, 19L, 15L, 13L), y = c(56L, 31L, 40L, 43L, 20L, 
45L, 55L, 8L, 43L, 26L, 7L, 52L, 7L, 31L, 11L, 14L, 55L, 26L, 
4L, 42L, 34L, 44L, 12L, 4L, 30L, 60L, 23L, 44L, 29L, 55L, 6L, 
37L, 11L, 14L, 36L, 52L, 28L, 22L, 31L, 33L)), .Names = c("x", 
"y"))), .Names = c("file1", "file2"))

Upvotes: 0

Roland
Roland

Reputation: 132576

Not tested due to lack of a reproducible example:

for (i in seq_along(QQJAN)) {
  pdf(sprintf("plot%i.pdf", i)) #or pdf(paste0(names(QQJAN)[i], ".pdf"))
    plot(QQJAN[[i]])
  dev.off()
}

If you are only interested in side effects, such as plotting, a for loop is usually appropriate. You should use lapply if you need a return value.

Upvotes: 1

Related Questions