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]
...
任何人有任何想法?
非常感謝
感謝那!雖然我應該對其他讀者說,這隻適用於等長度的載體。我不得不略微修改'winter.totals'長度爲75而不是74。 – boro141 2014-12-05 11:08:51