R创建功能以添加年份列 [英] R Create function to add water year column

查看:134
本文介绍了R创建功能以添加年份列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要为时间序列创建一个水年栏。美国水年来自10月至9月,被认为是年末。例如,2014年的水年是2013年10月1日 - 2014年9月30日。

I want to be able to create a water year column for a time series. The US water year is from Oct-Sept and is considered the year it ends on. For example the 2014 water year is from October 1, 2013 - September 30, 2014.

这是美国的水年,而不是唯一的水年。因此,我想输入一个开始月份,并为日期计算一个水年。

This is the US water year, but not the only water year. Therefore I want to enter in a start month and have a water year calculated for the date.

例如,如果我的数据看起来像

For example if my data looks like

        date
2008-01-01 00:00:00
2008-02-01 00:00:00
2008-03-01 00:00:00
2008-04-01 00:00:00
       .
       .
       .
2008-12-01 00:00:00

我希望我的功能工作如:

I want my function to work something like:

wtr_yr <- function(data, start_month) {

does stuff

}

然后我的输出将是

wtr_yr(data, 2)

         date                    wtr_yr
    2008-01-01 00:00:00           2008
    2008-02-01 00:00:00           2009 
    2008-03-01 00:00:00           2009
    2008-04-01 00:00:00           2009
           .
           .
           .
    2009-01-01 00:00:00           2009 
    2009-02-01 00:00:00           2010
    2009-03-01 00:00:00           2010
    2009-04-01 00:00:00           2010

我开始将日期分成不同的列,但我不认为这是最好的办法。任何建议?

I started by breaking the date up into separate columns, but I don't think that is the best way to go about it. Any advice?

提前感谢

推荐答案

我们可以使用POSIXlt来一个答案。

We can use POSIXlt to come up with an answer.

wtr_yr <- function(dates, start_month=9) {
  # Convert dates into POSIXlt
  dates.posix = as.POSIXlt(dates)
  # Year offset
  offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
  # Water year
  adj.year = dates.posix$year + 1900 + offset
  # Return the water year
  adj.year
}

我们现在在一个例子中使用此功能。

Let's now use this function in an example.

# Sample input vector
dates = c("2008-01-01 00:00:00",
"2008-02-01 00:00:00",
"2008-03-01 00:00:00",
"2008-04-01 00:00:00",
"2009-01-01 00:00:00",
"2009-02-01 00:00:00",
"2009-03-01 00:00:00",
"2009-04-01 00:00:00")

# Display the function output
wtr_yr(dates, 2)

# Combine the input and output vectors in a dataframe
df = data.frame(dates, wtr_yr=wtr_yr(dates, 2))

这篇关于R创建功能以添加年份列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆