0

我有一个如下所示的数据框:

set.seed(50)
df <- data.frame(Month=c(sort(sample(1:12, 10)),
                         sort(sample(1:12, 10)),
                         sort(sample(1:12, 10))),
                 Year=c(rep(2007, 10), 
                        rep(2010, 10), 
                        rep(2011, 10))) 

负责人df

  Month Year
1     1 2007
2     3 2007
3     4 2007
4     5 2007
5     6 2007
6     7 2007

我需要根据季节重新编码年份变量,例如,如果月份是一月,年份是 2013 年,那么年份应该重新编码为 2012/2013。对于 1-6 月,年份应重新编码为 2012/2013,对于 7-12 月应重新编码为 2013/2014。

df因此应重新编码如下。请注意,缺少某些月份和缺少某些年份:

set.seed(50)
df <- data.frame(Month=c(sort(sample(1:12, 10)),
                         sort(sample(1:12, 10)),
                         sort(sample(1:12, 10))),
                 Year=c(rep(2007, 10), 
                        rep(2010, 10), 
                        rep(2011, 10)),                   
                 Year.Seasonal=c(rep('2006/2007', 5),
                                 rep('2007/2008', 5),
                                 rep('2009/2010', 6),
                                 rep('2010/2011', 9),
                                 rep('2011/2012', 5)))

重新编码的负责人df

  Month Year Year.Seasonal
1     1 2007     2006/2007
2     3 2007     2006/2007
3     4 2007     2006/2007
4     5 2007     2006/2007
5     6 2007     2006/2007
6     7 2007     2007/2008

这样做的最佳方法是什么?

4

2 回答 2

4
df <- within(df,season <- paste(Year - (Month <= 6),
                                Year + (Month > 6),sep="/"))
head(df)
  Month Year    season
1     1 2007 2006/2007
2     3 2007 2006/2007
3     4 2007 2006/2007
4     5 2007 2006/2007
5     6 2007 2006/2007
6     7 2007 2007/2008
于 2013-03-16T17:34:55.117 回答
2

这是使用的解决方案ifelse()- 如果Month小于 7,则将是上一季,如果不是,则为下一季。功能paste()将放在一起年。

df$Year.Seasonal<-ifelse(df$Month<7,
     paste(df$Year-1,df$Year,sep="/"),paste(df$Year,df$Year+1,sep="/"))

> head(df)
  Month Year Year.Seasonal
1     1 2007     2006/2007
2     3 2007     2006/2007
3     4 2007     2006/2007
4     5 2007     2006/2007
5     6 2007     2006/2007
6     7 2007     2007/2008
于 2013-03-16T17:29:50.237 回答