R重复矩阵循环

R repeat a matrix recycle

我有一个时间序列数据矩阵,如下所示,我想为其创建 104 个副本。 原始数据样本如下(总数据包括104年月流量)

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

等等

第一次复制与原始数据相同,但对于第二次复制,streamflow 来自第二年的第一个月,第三次复制,streamflows 来自第三年的第一个月,依此类推.它在到达数据集末尾时回收。第一、第二、第三次复制示例如下:

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

注意:复制第 2 年的 3 个,依此类推

谢谢

您可以尝试这样的操作:

# Create function to reorder a given variable 'x' (analagous to streamflow), putting everything before zth observation at end   
f = function(x, z) {  
    c(z:x[length(x)], 1:(z - 1))
}

# Create dataset for testing
X_orig = data.frame(rep(1:12, 104), rep(1:104, each = 12), 1:(104 * 12)) #pretend this is your data
colnames(X_orig) = c("Month", "Year", "Streamflow") 

# Create your 104 replicates    
L = list() # to store replicates
year_inds = which(1:nrow(X_orig) %% 12 == 1) #implement function 'f' every year i.e. on 1st, 13th, 24th.. obs
k = 1 # counter
for (i in 1:nrow(X_orig)) {
  if (i %in% year_inds) {
    X = X_orig
    X$Replicate = k 
    if (i != 1) { #first replicate should be same as original data
      X$Streamflow = fun(X$Streamflow, i)
    }
    L[[k]] = X; k = k +1
  }
}

下面的post回答了上面的问题。有两种方法,一种是 for-loop,有一个很好的建议可以让它更快。