-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpat_trimDate.R
96 lines (77 loc) · 2.46 KB
/
pat_trimDate.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#' @export
#' @importFrom rlang .data
#'
#' @title Trim a PurpleAir Timeseries object to full days
#'
#' @param pat PurpleAir Timeseries \emph{pat} object.
#'
#' @description Trims the date range of a \emph{pat} object to local time date
#' boundaries which are \emph{within} the range of data. This has the effect
#' of removing partial-day data records and is useful when calculating
#' full-day statistics.
#'
#' @return A subset of the given \emph{pat} object.
#'
#' @examples
#' library(AirSensor)
#'
#' UTC_days <-
#' pat_filterDate(
#' example_pat,
#' startdate = 20220702,
#' enddate = 20220705,
#' timezone = "UTC"
#' )
#'
#' pat_multiPlot(UTC_days)
#'
#' local_days <- pat_trimDate(UTC_days)
#' pat_multiPlot(local_days)
#'
pat_trimDate <- function(
pat = NULL
) {
# ----- Validate parameters --------------------------------------------------
MazamaCoreUtils::stopIfNull(pat)
if ( !pat_isPat(pat) )
stop("Parameter 'pat' is not a valid 'pa_timeseries' object.")
if ( pat_isEmpty(pat) )
stop("Parameter 'pat' has no data.")
# Remove any duplicate data records
pat <- pat_distinct(pat)
# ----- Get the start and end times ------------------------------------------
timeRange <- range(pat$data$datetime)
timezone <- pat$meta$timezone
# NOTE: The dateRange() is used to restrict the time range to days that have
# NOTE: complete data.
# NOTE:
# NOTE: floor/ceiling the start date depending on whether you are already
# NOTE: at the date boundary
hour <-
MazamaCoreUtils::parseDatetime(timeRange[1], timezone = timezone) %>%
lubridate::hour() # hour resolution is good enough to count as an entire day
if ( hour == 0 ) {
ceilingStart = FALSE
} else {
ceilingStart = TRUE
}
dateRange <-
MazamaCoreUtils::dateRange(
startdate = timeRange[1],
enddate = timeRange[2],
timezone = timezone,
unit = "sec",
ceilingStart = ceilingStart, # date boundary *after* the start
ceilingEnd = FALSE # date boundary *before* the end
)
# ----- Subset the "pat" object ----------------------------------------------
data <-
pat$data %>%
dplyr::filter(.data$datetime >= dateRange[1]) %>%
dplyr::filter(.data$datetime < dateRange[2])
pat$data <- data
# ----- Return ---------------------------------------------------------------
# Remove any duplicate data records
pat <- pat_distinct(pat)
return(pat)
}