将季节性降雨总量提取为新的向量的算法

时间:2014-12-04 16:54:49

标签: r if-statement for-loop

每个季节我有四个向量,包含1926年至1999年期间每个季节的降雨量。我正在尝试创建一个新的向量yearly.totals,它将从季节性向量中提取元素,使得它将包含按年份排序的每个季节的降雨量。它应该是:

yearly.totals[1] = spring.totals[1]
yearly.totals[2] = summer.totals[1]
yearly.totals[3] = fall.totals[1]
yearly.totals[4] = winter.totals[1]
yearly.totals[5] = spring.totals[2]
yearly.totals[6] = summer.totals[2]
...

注意我的'年'从春天开始。到目前为止,我已经尝试了以下代码:

year.length = length(spring.totals)+length(summer.totals)+length(fall.totals)+length(winter.totals)

yearly.totals = vector("numeric", year.length)

for(i in 1:length(yearly.totals)){
  if(i %in% seq(1,75,4)) {
    yearly.totals[i] = spring.totals[i]
  } else if(i %in% seq(2,75,4)) {
    yearly.totals[i] = summer.totals[i]
  } else if(i %in% seq(3,75,4)) {
    yearly.totals[i] = fall.totals[i]
  } else {
    yearly.totals[i] = winter.totals[i]
  }
}

使用seq()确定每个元素属于哪个季节。问题在于它从季节性向量中提取哪个元素。前四个元素是正确的,但之后就出错了。这就是:

yearly.totals[5] = spring.totals[5]
yearly.totals[6] = summer.totals[6]
...

我认为解决方案可能在于将for循环中的季节性i组件更改为i以外的其他组件,但我无法弄明白。我尝试了i - (i-1),这对前四个元素来说很好,但后来才重复。

for(i in 1:length(yearly.totals)){
  if(i %in% seq(1,75,4)) {
    yearly.totals[i] = spring.totals[i - (i-1)]
  } else if(i %in% seq(2,75,4)) {
    yearly.totals[i] = summer.totals[i - (i-1)]
  } else if(i %in% seq(3,75,4)) {
    yearly.totals[i] = fall.totals[i - (i-1)]
  } else {
    yearly.totals[i] = winter.totals[i - (i-1)]
  }
}

yearly.totals[5] = spring.totals[1]
yearly.totals[6] = summer.totals[1]
...

有人有什么想法吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

rbind将您的向量转换为矩阵 r ,并使用as.vector将矩阵转换为向量,这将按列逐列读取矩阵:

> spring.totals <- 1:10
> summer.totals <- 11:20
> fall.totals <- 21:30
> winter.totals <- 31:40
> 
> as.vector(rbind(spring.totals,summer.totals,fall.totals,winter.totals))
 [1]  1 11 21 31  2 12 22 32  3 13 23 33  4 14 24 34  5 15 25 35  6 16 26 36  7
[26] 17 27 37  8 18 28 38  9 19 29 39 10 20 30 40