Rewriting duplicated

PUBLISHED ON FEB 6, 2018

Lightning post. I got very confused earlier today on how to use duplicated. Basically, I didn’t know if it was picking only one duplicate or many of the duplicates at the same time. I figure it out but I still was a bit confused so I decided to rewrite the function from scratch. Below you can see it. Please post any other solutions or feedback.

dupl_identifier <- function(vec, where) {
  intm <- x %in% vec
  pos <- which(intm)
  intm[where(pos)] <- FALSE
  intm
}

my_duplicated <- function(x, fromLast = FALSE) {
  
  where <- ifelse(!fromLast, min, max)
  repeated <- names(which(table(x) > 1))
  
  if (length(repeated) == 0) return(rep(FALSE, length(x)))
  
  val <- lapply(repeated, dupl_identifier, where)
  final <- as.logical(Reduce(`+`, val))
  
  final
}
x <- sample(1:10, 100, replace = TRUE)

identical(my_duplicated(x),
          duplicated(x))
## [1] TRUE
x <- sample(c(1:100, NA), 100, replace = TRUE)

identical(my_duplicated(x),
          duplicated(x))
## [1] TRUE
TAGS: R
comments powered by Disqus