Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping months by winter season instead of year in R

Tags:

r

I have got the following data frame

year <- c(1949, 1950, 1950, 1950, 1951, 1951, 1951, 1952, 1952, 1952, 1953, 1953, 1953)
month <- c(12, 1, 2, 12, 1, 2, 12, 1, 2, 12, 1, 2, 12)
df <- data.frame(year, month)
 df
   year month
1  1949    12
2  1950     1
3  1950     2
4  1950    12
5  1951     1
6  1951     2
7  1951    12
8  1952     1
9  1952     2
10 1952    12
11 1953     1
12 1953     2
13 1953    12

where month 1 is January and month 12 is December. now I would like to group them by winter season. this would mean that for example month 12 from year 1949 would be grouped with month 1 and 2 from 1950 because they are part of 1 winter season. the ideal outcome would be:

 year month winterseason
1  1949    12            1
2  1950     1            1
3  1950     2            1
4  1950    12            2
5  1951     1            2
6  1951     2            2
7  1951    12            3
8  1952     1            3
9  1952     2            3
10 1952    12            4
11 1953     1            4
12 1953     2            4
13 1953    12            5 

any ideas?

like image 345
Judith Avatar asked Nov 03 '25 05:11

Judith


1 Answers

If this is already arranged by the month

df$winterseason <- cumsum(df$month == 12)
df$winterseason
#[1] 1 1 1 2 2 2 3 3 3 4 4 4 5
like image 148
akrun Avatar answered Nov 06 '25 00:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!