Skip to content

Instantly share code, notes, and snippets.

@troyhill
Last active December 19, 2015 18:18
Show Gist options
  • Select an option

  • Save troyhill/5997260 to your computer and use it in GitHub Desktop.

Select an option

Save troyhill/5997260 to your computer and use it in GitHub Desktop.
An R function to create columns with sequential tide numbers (for whole tidal cycles, flood, and ebb tides)
### Important note: I'm no longer maintaining this gist, since this code is incorporated into the
### VulnToolkit package.
### Because it's not being maintained, the code below might not work. The latest, updated version
### is available at:
### https://github.com/troyhill/VulnToolkit/blob/master/R/number_tides.R
### function to number tides and insert tide numbers (for whole tidal cycles, flood, and ebb tides)
### in high-frequency dataset.
### Requires HL() function output, and initial dataset
### input arguments:
### "data": full water level dataframe
### "datetime": date/time column from full dataset (used as "time" argument in HL())
### "hl": high-low function output (https://gist.github.com/troyhill/5489261)
###
### Have a problem? Find a bug? Email [email protected]
number.tides <- function(data, datetime, hl) {
data$ht.ind <- ifelse(datetime %in% hl$time[hl$tide == "H"], 1, 0)
data$lt.ind <- ifelse(datetime %in% hl$time[hl$tide == "L"], 1, 0)
data$tide.no <- cumsum(data$lt.ind) # number tidal cycles
# number the flood and ebb tides (include numbers *only* on flood and ebb tides)
data$ht.temp <- cumsum(data$ht.ind)
data$index <- c(1:nrow(data))
if(data$index[data$ht.temp == "1"][1] - data$index[data$tide.no == "1"][1] > 0){ # positive value: low tide first
data$ebb.fld <- ifelse(data$ht.temp == data$tide.no, 1, 0) # 1 = ebb tide; 0 = flood tide
} else { data$ebb.fld <- ifelse(data$ht.temp > data$tide.no, 1, 0)
}
data$fld.no <- ifelse(data$ebb.fld == 0, data$tide.no, NA)
data$ebb.no <- ifelse(data$ebb.fld == 1, data$tide.no, NA)
drop <- c("ht.temp", "index")
data <- data[, !(names(data) %in% drop)]
invisible(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment