title: How to handle "subscript out of bounds" error inside a function? in R
body: <p>I have a dataframe like this </p>
  
  <pre><code>Datetime &lt;- c("2016-03-03 05:30:13", "2015-03-02 12:45:00", "2016-03-01 02:53:20", "2016-02-28 03:22:18", 
                "2016-03-02 09:42:10", "2016-03-01 20:55:50", "2016-02-28 21:14:10", "2016-02-26 05:42:16",
                "2016-03-02 08:31:15", "2016-03-02 09:13:10", "2016-03-01 00:45:14", "2016-02-26 05:56:00", 
                "2016-02-02 13:44:00", "2016-02-02 14:41:20", "2016-02-01 15:33:10", "2016-01-25 04:24:00",
                "2016-03-02 17:24:12", "2016-03-01 17:28:16", "2016-02-28 18:22:34", "2016-02-27 02:34:31")
  
  ID &lt;- c("A","A","A","A","B","B","B","B","C","C","C","C","D","D","D","D","E","E","E","E")
  PT &lt;- c(27,35,38,22,35,39,7,15,37,25,38,42,45,19,17,25,32,35,39,26)
  
  df &lt;- data.frame(Datetime,ID,PT)
  df$Datetime &lt;- as.POSIXct(df$Datetime,format="%Y-%m-%d %H:%M:%S")
  </code></pre>
  
  <p>I use these lines to set the datetimes that I want to subset</p>
  
  <pre><code>today &lt;- as.POSIXlt(Sys.time())
  today$mday &lt;- today$mday 
  today$hour = "6"
  today$min = "30"
  today$sec = "0"
  Back2weeks &lt;- today   
  Back1day &lt;- today 
  Back2weeks$mday &lt;- Back2weeks$mday-14
  Back1day$mday &lt;- Back1day$mday-1
  </code></pre>
  
  <p>I am trying to use functions to create ggplots to output plots automatically for every ID and I do it this way </p>
  
  <pre><code>plots &lt;- function(a) { 
    if (nrow(a)&gt;0) { 
      ggplot(data = a,aes(x=Datetime,y=PT)) + geom_line(size = 0.5) + geom_point(size=3) 
    } 
  }
  
  lss&lt;-list()
  plot_lss&lt;-list()
  UniqueID &lt;- summaryBy(ID~ID, data = df, FUN = function(x) { c(n = length(x)) } )
  
  for (j in 1:(nrow(UniqueID))) 
  { 
    cat(j) 
    id &lt;- as.character(UniqueID$ID[[j]]) 
  
    df1 &lt;- subset(df, ID == id)
    df2 &lt;- subset(df1, df1$Datetime&gt;Back2weeks &amp; df1$Datetime&lt;today)
  
    lss[[j]] &lt;- df2
  
    plotdata &lt;- subset(df2, ID == id)
  
    plot_lss[[j]] &lt;- plots(plotdata)
    print(plot_lss[[j]])
    Sys.sleep(0)
  }
  </code></pre>
  
  <p>While this runs for the first 3 plots, the 4th plot doesn't show up since the datetime for the ID is out of my subset range. Now the function stops here and throws an error saying "<strong>Error in plot_lss[[j]] : subscript out of bounds</strong>", which is fine but I want the function to continue running and output the 5th plot which has a datetime within range. How would I make the function to keep running till the end and prevent exiting out of the loop in this case? Kindly please provide your thoughts in this.  </p>