#' Return unique values
#'
#' Function that returns the number of unique values in a particular vector
#'
#' @param x vector
#' @param ... additional arguments passed to `base::unique`
#'
#' @return number of unique values in the input vector
#' @export
n.unique <- function(x, ...){
length(unique(x, ...))
}
#' Check if all values in a vector are the same
#'
#' @param xx A vector
#' @param na.rm should NA values be omitted
#' @param fail_if_na should function return FALSE when NA values are present
#' @param ... additional arguments passed to `base::unique`
#'
#' @return logical value indicating whether all values in the vector were equal
#' @importFrom stats na.omit
#' @export
#'
#' @examples
#' all_same( c(rep(0, 10), NA) )
#' all_same( c(rep(0, 10), NA), na.rm=TRUE )
#' all_same( rep(NA, 10) )
#' all_same( rep(NA, 10), na.rm=TRUE )
#' all_same( rep(NA, 10), na.rm=FALSE, fail_if_na=TRUE )
all_same = function(xx, na.rm = FALSE, fail_if_na = FALSE, ...){
uu = unique(xx, ...)
if( na.rm ){
uu = na.omit(uu)
} else if( any(is.na(uu)) ){
if(fail_if_na){
warning("Returned FALSE because of NA values")
return(FALSE)
} else if( length(uu) == 2 ){
warning("all equal except for NA values. set `na.rm=TRUE` to exclude these")
}
}
return( length(uu) == 1 )
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.