R创建函数以添加水年列 [英] R Create function to add water year column
问题描述
我希望能够为时间序列创建水年列.美国的水年是从 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屋!