R/leadtrail.R In trnnick/TStools: Time Series Analysis Tools and Functions

```leadtrail <- function(x,rm=c("zeros","na"),lead=c(TRUE,FALSE),trail=c(TRUE,FALSE)){
# Function to remove leading/trailing zeros or NAs
#
# Inputs:
#   x         Vector of values to check.
#   rm        What to remove, can be "zeros" or "na".
#   trail     Remove trailing values: TRUE or FALSE.
#
# Output:
#   y         Resulting vector
#
# Example:
#   x <- c(rep(0,5),rnorm(100),rep(0,5))
#   print(x)
#   print(y)
#
# Nikolaos Kourentzes, 2016 <[email protected]>

# Defaults
rm <- rm[1]
trail <- trail[1]

# Select what to remove
if (rm=="zeros" | rm=="z"){
idx <- which(x == 0)
} else if (rm=="na" | rm=="n"){
idx <- which(is.na(x))
} else {
stop("Incorrect rm choice.")
}

n <- length(x)
l <- length(idx)

if (idx[1]==1){
d.idx <- diff(idx)
loc <- which(d.idx > 1)[1]
if (is.na(loc)){
loc <- l
}
} else {
}

} else {
}

# Handle trailing observations
if (trail==TRUE & l>0){

if (tail(idx,1)==n){
d.idx <- diff(rev(idx))
loc <- which(d.idx != -1)[1]
if (is.na(loc)){
loc <- l
}
trail.rm <- (n-loc+1):n
} else {
trail.rm <- NULL
}

} else {
trail.rm <- NULL
}

keep <- rep(TRUE,n)