2014-12-04 62 views
0

我有四個向量包含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] 
... 

相信該解決方案可能在於中不斷變化的季節性i個分量for循環不僅僅是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] 
... 

任何人有任何想法?

非常感謝

回答

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 
+0

感謝那!雖然我應該對其他讀者說,這隻適用於等長度的載體。我不得不略微修改'winter.totals'長度爲75而不是74。 – boro141 2014-12-05 11:08:51