Saving and Loading Zoo Objects in R: A Simplified Approach

To save and read the data again as a zoo object, you can modify the code slightly. Here’s an updated version:

library(xts)
df2 <- by(dat, dat$nodeId, function(x){
  ends <- endpoints(x, on = "minutes", k = 1)
  xx <- period.apply(x, ends, mean)
})

# Save as a zoo object
saveRDS(df2, "df2.zoo")

# Read from the saved file
df2_read <- readRDS("df2.zoo")

In this code:

  • We use by to group the data by nodeId and then apply the calculation within each group.
  • We save the result as a zoo object using saveRDS.
  • We read the saved file back into R using readRDS.

Note that we don’t need to specify the index or tz when reading from the saved file, as these are already included in the zoo object.


Last modified on 2023-10-08