0

I need to run a code on many data sets (like df.p2, df.p3) to get charts. Following is the data format that I have.

< df.p1
  Date    Sales
Jan 2011  1000
Feb 2011  1120
Mar 2011  1050
.
.
.

Like this I have a list of data frames, now I want to run the following code in a loop.

ggplot(df.p1, aes(Date,Sales))+
      geom_line()+
     xlab("Month") + ylab("Sales") + 
     ggtitle("Sales-Product1")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Learner
  • 206
  • 5
  • 18
  • 3
    `lapply(list.of.dfs, function(x){ggplot(x, ......)})` – LAP Jul 26 '18 at 11:34
  • 1
    Because it looks like you will need to use different titles for each dataset, you might want to consider a nested list column and a title column in the same tibble dataset (if using `tidyverse` and `purrr` within it) You could then run `walk2` over a function containing the ggplot2 command, passing the title and data objects as arguments to this. – JonMinton Jul 26 '18 at 11:38
  • @LAP Thanks it worked well! – Learner Jul 26 '18 at 14:25

1 Answers1

0

Data:

dates <- as.Date(as.Date("2011-12-30"):as.Date("2012-05-04"), origin="1970-01-01")
Date<-c()
Sales<-c()
    for (i in 1:10) {
    assign(paste0("df.p",i),cbind.data.frame(Date=sample(dates,5),Sales=rnorm(5,1000,100)    )) }

Function:

lapply(paste0("df.p",1:10), function(x){ggplot(data=eval(parse(text = x)) ,aes(Date,Sales))+geom_line()+xlab("Month")+ylab("Sales")+ggtitle(paste0("Sales-Product for dataset ",x))})
Iman
  • 2,224
  • 15
  • 35