R创建添加水年列的功能

Jef*_*ton 2 datetime r date time-series

我希望能够为时间序列创建一个水年专栏.美国水年是从10月到9月,被认为是结束的一年.例如,2014年水年是2013年10月1日至2014年9月30日.

这是美国的水年,但不是唯一的水年.因此,我想在开始月份输入,并计算该日期的水年.

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

        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
Run Code Online (Sandbox Code Playgroud)

我希望我的功能像以下一样工作:

wtr_yr <- function(data, start_month) {

does stuff

}
Run Code Online (Sandbox Code Playgroud)

那我的输出就是

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
Run Code Online (Sandbox Code Playgroud)

我开始将日期分成不同的列,但我不认为这是最好的方法.有什么建议?

提前致谢!

Can*_*ner 5

我们可以使用POSIXlt来得出答案.

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
}
Run Code Online (Sandbox Code Playgroud)

现在让我们在一个例子中使用这个函数.

# 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))
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用USGS R packge"smwrBase"中提供的waterYear函数(可从https://github.com/USGS-R/smwrBase获得).此包中还有其他有用的水文分析工具. (3认同)