【问题标题】:R repeat a matrix recycleR 重复矩阵循环
【发布时间】:2018-01-30 02:18:36
【问题描述】:

我有一个如下的时间序列数据矩阵,我想创建 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

等等

第一个副本与原始数据相同,但第二个副本的流量来自第二年的第一个月,第三个副本的流量来自第三年的第一个月,依此类推。它在到达数据集的末尾时回收。第一次、第二次和第三次复制的例子如下:

月年复制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 次循环,依此类推

谢谢

【问题讨论】:

  • 表格末尾会发生什么。月份和年份没有变化,这些条目是否被删除?
  • 我编辑了文本。
  • 对不起,我又改了问题。

标签: r repeat recycle


【解决方案1】:

你可以试试这样的:

# 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
  }
}

【讨论】:

    【解决方案2】:

    下面的帖子回答了上述问题。有两种方法,一种是 for 循环,有一个很好的建议可以加快速度。

    R how to make loop faster

    【讨论】: