Skip to content

Instantly share code, notes, and snippets.

@njudd
Last active October 21, 2025 14:37
Show Gist options
  • Select an option

  • Save njudd/00f94cfe365114fe1c9018a2b40d7809 to your computer and use it in GitHub Desktop.

Select an option

Save njudd/00f94cfe365114fe1c9018a2b40d7809 to your computer and use it in GitHub Desktop.
Outlier Removal (5SD to NA)
outs5SD <- function(vec, n_outsONLY = FALSE){
m = mean(vec, na.rm = T)
s = sd(vec, na.rm = T)
# if less than 5 sd below or above the mean replace with na's
print(paste0(length(vec[vec < m - s*5 | vec > m + s*5]), " number of outliers above or below 5SD"))
vec[vec < m - s*5 | vec > m + s*5] <- rep(NA, length(vec[vec < m - s*5 | vec > m + s*5]))
if(n_outsONLY == FALSE) {
return(vec)
} else {} # no return of vector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment