keep_every: Keep every other element of a vector, flexibly

View source: R/vector_tools.R

keep_everyR Documentation

Keep every other element of a vector, flexibly

Description

Use a string to keep every nth element of a vector, e.g. "k-" to keep odd elements, "–k" to keep every third element, or "k-k–" to keep every 1st and 3rd element for every 5 entries. Use k, y, or t to keep an element, and any other character to remove it.

Usage

keep_every(vec, key = "k-")

Arguments

vec

(Vector) Any vector.

key

(Character or Other) A string that controls which elements to keep (with k or y or t) and which elements to omit (any other character). This string can be arbitrarily long; it is recycled along the length of vec. If you pass a different kind of vector to key (e.g. a numeric vector or a logical vector), then its elements will be coerced with as.logical() and TRUE values will keep elements, and FALSE or NA values will remove them.

Details

You can also pass other vector types into key, and they will be coerced into a logical vector where TRUE keeps elements and FALSE or NA removes them.

Value

A vector of the same type as vec, but shortened according to key.

Authors

Examples


# By default, keeps every odd element (1st, 3rd, etc.) using "k-".
keep_every(letters)

## [1] "a" "c" "e" "g" "i" "k" "m" "o" "q" "s" "u" "w" "y"

# Keep every even element
keep_every(letters, "-k")

## [1] "b" "d" "f" "h" "j" "l" "n" "p" "r" "t" "v" "x" "z"

# Use k/y/t to keep an element, any other character to remove it.
# For every 3 elements, keep the 1st and 3rd
keep_every(letters, "yny")

## [1] "a" "c" "d" "f" "g" "i" "j" "l" "m" "o" "p" "r" "s" "u" "v" "x" "y"

# Pass in a vector to use it as a coerced logical vector
keep_every(letters, c(1, 0, 0, 2))
## [1] "a" "d" "e" "h" "i" "l" "m" "p" "q" "t" "u" "x" "y"


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