title: Is there a way to pass a subset of time series data with the map or lapply command in r?
body: <p>To improve my R programming and simplify my code, I'm trying to replace a 'for' loop with 'lapply', 'map', or a similar variant.  I want to perform a function using 2 minute time intervals from my time series data.  When I try to pass just a subset of the data using one of the functionals, 'map' or 'lapply', I get a 'subscript out of bounds error'.  Any ideas?</p>
  
  <pre><code>library(lubridate)
  library(purrr)
  library(stats)
  library(xts)
  # Set up the time series data
  t &lt;- ymd_hms("2020-01-01 08:00:00","2020-01-01 08:01:00","2020-01-01 08:02:00", "2020-01-01 08:03:00")
  tsData &lt;- as.xts(1:4,order.by=(t))
  # Set up the summary time periods; in this case every 2 minutes
  timeSlots &lt;- seq(from=t[1],to=t[length(t)],by=120)
  # Make sure it also summarizes the last period
  lastTime &lt;- stats::time(tsData[nrow(tsData)])
  
  # The next 4 lines iterate through the time series and print a summary for each 2 minute time period; 
  # This is the loop I want to replace with 'map'
  for (i in 1:(length(timeSlots))) {
    if (i &lt; length(timeSlots)) {
      print (summary (tsData[paste(timeSlots[i],'/',(timeSlots[i+1]-1),sep='')]))
    }
  # This makes sure the last subset includes the last observation
    else print (summary (tsData[paste(timeSlots[i],'/',lastTime,sep='')]))
  }
  
  # This next statement gets a subscript out of bounds error
  lapply (timeSlots, function(x) summary(tsData[x:x+1]))
  
  # This next statement gets a subscript out of bounds error
  map (timeSlots,function(x) summary(tsData[x:x+1]))
  </code></pre>