【问题标题】:Change year variable in dataframe depending on season根据季节更改数据框中的年份变量
【发布时间】:2013-03-16 17:23:28
【问题描述】:

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

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

最好的方法是什么?

【问题讨论】:

    标签: r


    【解决方案1】:
    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
    

    【讨论】:

    • 粘贴字符串的好方法!我应该记得更频繁地使用inside。
    • 非常感谢,我原以为这会比实际情况复杂得多。
    【解决方案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
    

    【讨论】:

    • 为什么不直接使用df$Month&lt;7
    • @Hemmo 你是对的——有时只是想得太复杂了:D
    • 经常发生在我身上:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2021-01-17
    • 2020-11-21
    • 2015-12-14
    相关资源
    最近更新 更多