0

I have a huge data with many subjects. The data has the following columns:

    ID  TIME   CONC
7030104 2.0    0.536
7030104 2.5    1.320
7030104 3.0    1.460
7030104 4.0    5.070
7030104 5.0    17.300
7030104 6.0    38.600
70304   8.0    0.589
70304   10.0   35.400
70304   12.0   29.400
70304   24.0   10.900
70304   36.0   3.260
70304   48.0   1.290

I would like to draw a separate plot (CONC versus TIME) for each subject ID and automatically save it to the working directory with the ID number of the subject.

I am using simple plotting but I need the help in how I can apply it for all subject IDs and automatically save the plots into my working directory.

setwd("..")
plotobj <- NULL
plotobj <- plot(sub$TIME,sub$CONC,type="b")

i am using RStudio

Your assistance is appreciated!

Amer
  • 2,131
  • 3
  • 23
  • 38

2 Answers2

0

First try getting the list of IDs

id_arr = unique(sub$ID)

After, save the plot for each possible ID

for(i in id_arr) {
    sub_id = subset(sub, ID == i)
    jpeg(paste(i, ".jpg", sep=""))
    plot(sub_id$TIME, sub_id$CONC, type="b")
    dev.off()
}
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Caner
  • 678
  • 2
  • 8
  • 11
0

You could save it in a single "pdf" file, single page per plot. The "title" of the plot identifies the subset "ID". Here, I am using lapply after splitting (split) the dataset by "ID". Specify the plot arguments ad wrap it in invisible so that the NULL loop won't get printed on the R console.

par(mfrow=c(1,1))
pdf('Amer.pdf')
lst <- split(df, df$ID)
invisible(lapply(lst, function(sub) with(sub, 
    plot(TIME, CONC, type='b', main= paste('Plot of', ID[1])) )))
dev.off()

Or if you need "separate", .jpg plots, lapply can still be used

 invisible(lapply(lst, function(sub) {
      jpeg(paste0(sub$ID[1],'.jpg'))
       with(sub, plot(TIME, CONC, type='b', main=paste('Plot of', ID[1])))
      dev.off()
      }))

data

df <- structure(list(ID = c(7030104L, 7030104L, 7030104L, 7030104L, 
7030104L, 7030104L, 70304L, 70304L, 70304L, 70304L, 70304L, 70304L
), TIME = c(2, 2.5, 3, 4, 5, 6, 8, 10, 12, 24, 36, 48), CONC = c(0.536, 
1.32, 1.46, 5.07, 17.3, 38.6, 0.589, 35.4, 29.4, 10.9, 3.26, 
1.29)), .Names = c("ID", "TIME", "CONC"), class = "data.frame",
row.names = c(NA, -12L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you akrun. Saving all into one pdf file is a cool thing, otherwise, I will be having 560 png files. Thank you for you assistance. – Amer Jan 06 '15 at 06:57
  • @Amer No problem. I always save it in pdf unless I have a couple of graphs that is needed for publication. – akrun Jan 06 '15 at 06:58
  • what type of graphs do you use for publications? I usually save them in pdf and then use the Photoshop to get high resolution ones for publication (usually TIFF). Is there a way to get publication quality graphs directly from R given journal specifications? (usually width of 500 pixels and resolution > 300 dpi) – Amer Jan 06 '15 at 07:07