title: Creating time series with loops and populating them with values
body: <p>I have a data frame, where each row represents a part of the time series. </p>
  
  <p>I need to create a total time series that stretches over several years, for up to several hundred units. </p>
  
  <p>So, each row sets a value for a certain period and then it needs to resume to the max given values (given by maks). </p>
  
  <p>See example here: </p>
  
  <p>Code: </p>
  
  <pre><code>library(tidyr)
  library(dplyr)
  
  # My data for 3 units
  df &lt;- structure(list(Unit = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
  3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Limit = c(850L, 
  655L, 500L, 1000L, 100L, 75L, 0L, 600L, 635L), Max = c(1310L, 
  1310L, 1310L, 1300L, 1300L, 1300L, 915L, 915L, 915L), startDate = structure(c(1483250400, 
  1430481600, 1546286400, 1421280000, 1498813200, 1546300800, 1420869600, 
  1527876000, 1463097600), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
  endDate = structure(c(1496275200, 1451520000, 1609459200, 
  1426431600, 1527811200, 1577836800, 1433170800, 1546383600, 
  1464807600), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
  -9L), class = "data.frame")
  
  
  # Doing a loop to create time series for each row
  d &lt;- NULL
  
  for(i in 1:nrow(df)) {
    d &lt;- rbind(d, data.frame(Date = seq.POSIXt(from = df$startDate[i], to = df$endDate[i], by = "hour"), 
                             value = df$Limit[i], 
                             unit = df$Unit[i]))
  
  }
  
  # Spread it out to a nice data frame
  d &lt;- spread(d, unit, value = value)
  
  # Left join on a global time series
  globalStart &lt;- as.POSIXct("2015-01-01 00:00:00", tz = "UTC")
  globalEnd &lt;- as.POSIXct("2021-12-01 00:00:00", tz = "UTC")
  
  dfResult &lt;- data.frame(Date = seq.POSIXt(from = globalStart, to = globalEnd, by = "hour"))
  
  # Now join it together
  dfResult &lt;- left_join(dfResult, d, by = "Date")
  
  # Add values to fill out NA with max
  maks &lt;- c(915, 1315, 900)
  
  dfResult[is.na(dfResult[, 2]), 2] &lt;- maks[1]
  dfResult[is.na(dfResult[, 3]), 3] &lt;- maks[2]
  dfResult[is.na(dfResult[, 4]), 4] &lt;- maks[3]
  
  # Final result
  dfResult
  </code></pre>
  
  <p>My problem is this takes around 35 minutes with my dataset, and this is on just 58 units, potentially I need to do it for thousand of units - and I need to speed this up drastically. </p>