Search code examples
rrepeatrecycle

R repeat a matrix recycle


I have a matrix of time series data as below and I want to create 104 replicates of it. The sample of original data as below (the total data include 104 years of monthly streamflows)

Month Year streamflow1 streamflow2 
1   1913    3632    703
2   1913    2274    407
3   1913    4047    566
4   1913    3226    538
5   1913    4027    911
6   1913    6772    1779
7   1913    5335    1401
8   1913    8138    1626
9   1913    9769    1993
10  1913    6243    1463
11  1913    11913   2694
12  1913    6024    1482
1   1914    3506    674
2   1914    2062    392
3   1914    2083    417
4   1914    1945    428
5   1914    3587    568
6   1914    4035    846
7   1914    7969    1620
8   1914    6218    1588
9   1914    3512    894
10  1914    2277    651
11  1914    1820    519
12  1914    2316    485
1   1915    1751    417
2   1915    1252    327
3   1915    1513    304
4   1915    1817    312
5   1915    4361    653
6   1915    6356    1282
7   1915    7726    1660
8   1915    8852    1586
9   1915    7314    1721
10  1915    8391    1783
11  1915    5968    1702
12  1915    4008    764

and so on

The first replicate is the same as the original data but for the second replicate, the streamflow is from the first month of the second year and the third replicate, streamflows is from the first month of the third year and so on. It recycles when reaches the end of dataset. The example of first, second, and third replicate are as follow:

month year replicate streamflow1 streamflow2 1 1913 1 3632 703 1 1913 2 3506 674 1 1913 3 1751 417 2 1913 1 2274 407 2 1913 2 2062 392 2 1913 3 1252 327 1 1914 1 3506 674 1 1914 2 1751 417 1 1914 3 3632 703 2 1914 1 2062 392 2 1914 2 1252 327 2 1914 3 2274 407

Note: replicate 3 of year 2 recycled and so on

Thanks


Solution

  • The post below answers the above question. There are two methods one with for-loop and there is a great suggestion to make it fast.

    R how to make loop faster