unique_n: Keep the first n unique elements in a vector

View source: R/vector_tools.R

unique_nR Documentation

Keep the first n unique elements in a vector

Description

Keep the first n unique elements in a vector

Usage

unique_n(vec, n, sort = "no")

Arguments

vec

(Vector) Any vector.

n

(Integer) The maximum number of elements to keep from vec. If n is greater than the number of elements in vec, the entirety of vec will be returned.

sort

(Character) "ascending" (or "asc" or "a") sorts vec in ascending order (the default order of sort()). "descending" (or "desc" or "d") sorts in reverse. Use "no" (or "n") to leave the elements of vec in their original order.

Value

A vector of the same type as vec.

Examples

set.seed(12345)
lets <- sample(letters[1:10], 50, replace = TRUE)

unique_n(lets, 10, sort = "no")

## [1] "c" "j" "h" "b" "f" "g" "a" "d" "i" "e"

unique_n(lets, 8, sort = "asc")

## [1] "a" "b" "c" "d" "e" "f" "g" "h"

unique_n(lets, 5, sort = "desc")

## [1] "j" "i" "h" "g" "f"

unique_n(1:5, 20)  # Asking for 20 elements, but there are only 5 uniques.

## [1] 1 2 3 4 5


DesiQuintans/desiderata documentation built on April 9, 2023, 5:43 a.m.