Search code examples
rfor-looptime-seriescalculated-columns

How do I write r code that loops for a time series?


I have a dataset of two columns, the year and temperature.

Year     Temperature
1869     51.4
1870     53.6
1871     51.1
1872     51.0
1873     51.0
1874     51.3
1875     49.4
1876     51.9
1877     52.8
1878     53.6
1879     52.3
1880     53.2
1881     52.4
1882     52.0
1883     50.5
1884     52.4
1885     51.1
1886     51.0
1887     50.9
1887     49.3

I need to write an r script to calculate the mean percent change every year, plot and print the output along with the original data.

For example the mean % change for 1873 = ((mean from 1874 to 1878 - mean from 1869 to 1873)/mean from 1874 to 1878)*100 I need to repeat this for 1874 to 1884, print the out in a csv file and plot as a time series along with the original data.

I am not sure to begin here, any ideas or suggestions welcome.


Solution

  • using library(zoo) we can do

    l = rollmean(head(x, -5)[,2], 5)
    r = rollmean(tail(x, -5)[,2], 5)
    percent_change = 100 * (r-l)/r
    # [1]  0.3474903  0.7692308  3.7907506  3.6700719  2.6944972  0.5376344  0.1919386 -2.0897833 -2.8404669
    #[10] -2.9699101 -2.2379270
    

    The data:

    x = structure(list(Year = c(1869, 1870, 1871, 1872, 1873, 1874, 1875, 
    1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 
    1887, 1887), Temp = c(51.4, 53.6, 51.1, 51, 51, 51.3, 49.4, 51.9, 
    52.8, 53.6, 52.3, 53.2, 52.4, 52, 50.5, 52.4, 51.1, 51, 50.9, 
    49.3)), class = "data.frame", row.names = c(NA, -20L))