R/duplicates.R

Defines functions duplicates

Documented in duplicates

#' Find All Indices of Duplicated Elements
#'
#' Unlike base R's 'duplicated' function, this function returns a vector of indices of all duplicated elements of a vector including the first instance.
#' @param vector A vector containing duplicated elements.
#' @param value Parameter similar to grep's: if FALSE, a vector containing the indices of all duplicated elements will be returned, but if TRUE, the offending elements themselves are returned.
#' @keywords duplicate copy same
#' @export
#' @examples
#' dup.vec <- c(1:9, 1:4, 11:15, 14:18)
#' duplicates(dup.vec)
#' [1] 1 2 3 4 10 11 12 13 17 18 19 20
#'
#' duplicates(dup.vec, value = TRUE)
#' [1] 1 2 3 4 1 2 3 4 14 15 14 15

duplicates <- function(vector, value = FALSE) {

  duplicated(x = vector, fromLast = FALSE) %>%
    which %>%
    c({ duplicated(x = vector, fromLast = TRUE) %>% which }) %>%
    sort %>%
    unique %>%
    { if ( value == TRUE ) { return(vector[.]) } else { return(.) } }

}
danjamesadams/Dantools documentation built on Aug. 24, 2019, 6:15 p.m.