Tag Archives: R

Simple function in R to calculate water year

###########################################################################
# Simple Water Year Function
###########################################################################
wtr_yr <- function(dates, start_month = 10) {
# Convert possible character vector into date
d1 = as.Date(dates)
# Year offset
offset = ifelse(as.integer(format(d1, “%m”)) < start_month, 0, 1)
# Water year
adj.year = as.integer(format(d1, “%Y”)) + offset
# Return the water year
return(adj.year)
}

Leave a Comment

Filed under ScriptingMemo

Handling date and date-time in R

Be careful with the time zone

> example = as.POSIXct(“1957-09-30 16:00:00”)

> example

[1] “1957-09-30 16:00:00 PST”

> as.Date(example)

[1] “1957-10-01”

> as.Date(example, tz = Sys.timezone())

[1] “1957-09-30”

The problem is that as.POSIXct() uses system timezone as default time zone and as.Date() uses UTC as default timezone.

Leave a Comment

Filed under ScriptingMemo