Skip to content

Instantly share code, notes, and snippets.

@jimjam-slam
Last active February 13, 2022 22:56
Show Gist options
  • Select an option

  • Save jimjam-slam/1952aeec83662ab8b8e7d69430604bbc to your computer and use it in GitHub Desktop.

Select an option

Save jimjam-slam/1952aeec83662ab8b8e7d69430604bbc to your computer and use it in GitHub Desktop.
Parse a vector of numeric times, given element-wise CF-complaint time dimension units (eg. "days since 1901-01-01") #rstatstips
# https://carbon.now.sh/iYHN1JgadkF76T9rXC7q
# parse_time_dimensions: given a numeric vector of dates or datetimes, and
# a character vector of the form "[units] since [epoch]", return a POSIXct
# vector of date-times that are parsed element-wise. useful if you have,
# say, a list of netcdfs with varied epochs and units.
# example:
# > test %>% mutate(target = parse_time_dimensions(n, t))
# # A tibble: 3 x 3
# n t target
# <int> <chr> <dttm>
# 1 1 days since 1900-01-01 00:00:00 1900-01-02 00:00:00
# 2 2 years since 1920-03-14 1922-03-14 00:00:00
# 3 3 months since 1960 1960-04-01 00:00:00
parse_time_dimensions <- function(counts, dimensions) {
require(tidyr)
require(dplyr)
require(purrr)
require(lubridate)
tibble(counts, dimensions) %>%
separate(dimensions, into = c('units', 'epochs'), sep = ' since ') %>%
mutate(
epoch_dts = parse_date_time(epochs, 'ymdHMS', truncate = 5),
units_fn = map(units,
~ switch(.x,
'microseconds' = microseconds,
'milliseconds' = milliseconds,
'seconds' = seconds,
'minutes' = minutes,
'hours' = hours,
'days' = days,
'months' = months,
'years' = years))) %>%
{
mutate(.,
dts = pmap(
select(., epoch_dts, units_fn, counts),
function(epoch_dts, units_fn, counts) {
epoch_dts + units_fn(counts)
}))
} %>%
unnest(dts) %>%
pull(dts)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment