boro141
boro141

Reputation: 65

Algorithm for extracting seasonal rainfall totals into a new vector

I have four vectors for each season containing the rainfall sum for each season in the period 1926 to 1999. I am trying to create a new vector yearly.totals which will extract elements from the seasonal vectors in such a way that it will contain the rainfall sums for each season ordered by year. It should read:

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]
...

Note my 'year' begins in Spring. So far I have tried the following code:

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

This identifies which season each element belongs to using seq(). The problem lies in which element it extracts from the seasonal vectors. The first four elements are correct but after that it goes wrong. This is what happens:

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

I believe the solution might lie in changing the seasonal ith component within the for loop to something other than just i, but I can't figure it out. I tried i - (i-1), which is fine for the first four elements but then just repeats.

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]
...

Anyone have any ideas?

Many thanks

Upvotes: 0

Views: 59

Answers (1)

Stephan Kolassa
Stephan Kolassa

Reputation: 8267

rbind your vectors into a matrix row-wise, and turn the matrix into a vector using as.vector, which will read the matrix column-wise:

> 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

Upvotes: 0

Related Questions