Skip to content

Instantly share code, notes, and snippets.

@troyhill
Created November 13, 2018 22:20
Show Gist options
  • Save troyhill/0d0ac909dc34c82a232b8bcf00cdc843 to your computer and use it in GitHub Desktop.
Save troyhill/0d0ac909dc34c82a232b8bcf00cdc843 to your computer and use it in GitHub Desktop.
identifies higher and lower high/low tides
assignTide <- function(data, timeCol = "time", levelCol = "level", tideCol = "tide") {
### this works well with output from HL()
### arguments:
### data = the data frame
### timeCol = name of column with time stamp data, in format "YYYY-MM-DD ..."
### levelCol = name of column with water level data (numeric)
### tideCol = name of column with tide indicator (H/L) - this is tailored to HL() output
data[, "day"] <- substr(data[, timeCol], 1, 10) # weak point - assumes YYYY-MM-DD format
data[, "tide2"] <- NA
for (i in 1:length(unique(data[, "day"]))) {
numLowTides <- sum(!is.na(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")]))
numHighTides <- sum(!is.na(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")]))
if (numHighTides == 2) {
# find higher & lower high tides
hh <- which.max(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")])
lh <- which.min(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")])
# define new tides
data[, "tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")][hh] <- "HH"
data[,"tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")][lh] <- "LH"
} else if (numHighTides == 1) {
### define value based on previous or subsequent values
data[,"tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "H")] <- rev(data[,"tide2"][(data[, tideCol] %in% "H") & (!is.na(data[,"tide2"]))])[2] # copy the second most recent HH/LH value (may bewrong if there's a gap in the data)
}
if (numLowTides == 2) {
hl <- which.max(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")])
ll <- which.min(data[, levelCol][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")])
data[,"tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")][hl] <- "HL"
data[,"tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")][ll] <- "LL"
} else if (numLowTides == 1) {
### define value based on previous or subsequent values
data[,"tide2"][(data[, "day"] == unique(data[, "day"])[i]) & (data[, tideCol] %in% "L")] <- rev(data[,"tide2"][(data[, tideCol] %in% "L") & (!is.na(data[,"tide2"]))])[2]
}
}
invisible(data)
}
### an example:
library(VulnToolkit)
data(NL_6min_2013)
nl.hl <- HL(level = NL_6min_2013[, 2], time = NL_6min_2013[, 1])
nl.hl <- assignTide(data = nl.hl)
head(nl.hl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment