Learner
Learner

Reputation: 757

saving figures like a loop until end of a data frame

I have a data like this and I want to save figures one after another by

df<- structure(list(x = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L, 4L, 4L, 4L, 4L), rn = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("AAAAA", 
"BBBBB", "CCCCC", "DDDDD"), class = "factor"), key = structure(c(2L, 
4L, 3L, 1L, 2L, 4L, 3L, 1L, 2L, 4L, 3L, 1L, 2L, 4L, 3L, 1L), .Label = c("WSAfrica", 
"Wscanada", "WSInida", "WSUSA"), class = "factor"), Median = c(0.000621, 
0.000777, 0.000574, 0.000537, 0.000381, 0.00177, 0.002, 0.000457, 
0.00247, 0.00199, 0.00287, 0.00224, 5.94e-05, 4.12e-05, 4.44e-05, 
5.68e-05), SD = c(0.000127453, 0.000107802, 0.001048659, 9.32e-05, 
9.23e-05, 0.000120554, 0.000914697, 0.000167046, 0.000125033, 
0.000410528, 0.000450444, 0.000310483, 5.91e-06, 8.98e-06, 1.11e-05, 
1.16e-05)), class = "data.frame", row.names = c(NA, -16L))

I tried the following function but I get an error saying that

Error in UseMethod("grid.draw") : no applicable method for 'grid.draw' applied to an object of class "function"

d_ply(df, .(rn),
      function(x) (ggplot(x, aes(x = x, y = Median))+
                     geom_point() +
                     scale_x_discrete(limit = c("Wscanada", "WSUSA", "WSInida","WSAfrica")) +
                     geom_errorbar(aes(ymin = Median-SD, ymax = Median+SD))+
                     ggsave(., filename =  paste0("", x$rn[1],".pdf"))))

Upvotes: 0

Views: 136

Answers (1)

csgroen
csgroen

Reputation: 2541

You're already adding the plot to ggsave, no need to use the . for the first argument:

d_ply(df, .(rn),
      function(x) (ggplot(x, aes(x = x, y = Median))+
                       geom_point() +
                       scale_x_discrete(limit = c("Wscanada", "WSUSA", "WSInida","WSAfrica")) +
                       geom_errorbar(aes(ymin = Median-SD, ymax = Median+SD))+
                       ggsave(filename =  paste0("", x$rn[1],".pdf"))))

Upvotes: 1

Related Questions