R/first_unique.R

Defines functions first_unique

Documented in first_unique

#' Retrieve the First Incidence of Each Element of a Vector
#'
#' This function returns a vector of indices of the first occurence of each unique element of a provided vector.
#' @param redundantvec The vector with repeated values. N.B. Providing a vector with no repeated values will return the equivalent of 1:length(redundantvec).
#' @keywords redundant unique
#' @export
#' @examples
#' arbitraryvec <- c(1:5, rep(c(6, 7), times = 3), 8:10)
#' length(arbitraryvec)
#' [1] 14
#'
#' first_unique(arbitraryvec)
#' [1] 1 2 3 4 5 6 7 12 13 14

first_unique <- function(redundantvec) {
# Given a vector, firstunique returns the index of the first occurence of every unique value.

  lapply(X = unique(redundantvec),
         FUN = function(un) { grep(pattern = un, x = redundantvec)[1] }) %>%
    unlist

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