i_keep(iterable, predicate)
constructs an iterator that filters
elements from iterable returning only those for which the predicate
is TRUE
.
Arguments
- iterable
an iterable object.
- predicate
a function that determines whether an element is
TRUE
orFALSE
. The function is assumed to take only one argument.- ...
passed along to iteror constructor.
Details
Originally called 'ifilter' from package
itertools
. Renamed because the order of arguments has changed
to put the iterable in the first argument, the better to be used
with the |>
operator.
Examples
# Filters out odd numbers and retains only even numbers
is_even <- function(x) {
x %% 2 == 0
}
it <- i_keep(1:10, is_even)
as.list(it)
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 4
#>
#> [[3]]
#> [1] 6
#>
#> [[4]]
#> [1] 8
#>
#> [[5]]
#> [1] 10
#>
# Similar idea here but anonymous function is used to retain only odd
# numbers
it2 <- i_drop(1:10, function(x) x %% 2 == 0)
nextOr(it2, NA) # 1
#> [1] 1
nextOr(it2, NA) # 3
#> [1] 3
nextOr(it2, NA) # 5
#> [1] 5
nextOr(it2, NA) # 7
#> [1] 7
nextOr(it2, NA) # 9
#> [1] 9
is_vowel <- function(x) {
x %in% c('a', 'e', 'i', 'o', 'u')
}
it3 <- i_keep(letters, is_vowel)
as.list(it3)
#> [[1]]
#> [1] "a"
#>
#> [[2]]
#> [1] "e"
#>
#> [[3]]
#> [1] "i"
#>
#> [[4]]
#> [1] "o"
#>
#> [[5]]
#> [1] "u"
#>
# Filters out even numbers and retains only odd numbers
is_even <- function(x) {
x %% 2 == 0
}
it <- i_drop(1:10, is_even)
as.list(it)
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 3
#>
#> [[3]]
#> [1] 5
#>
#> [[4]]
#> [1] 7
#>
#> [[5]]
#> [1] 9
#>
# Similar idea here but anonymous function is used to filter out odd
# numbers
it2 <- i_drop(1:10, function(x) x %% 2 == 1)
as.list(it2)
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 4
#>
#> [[3]]
#> [1] 6
#>
#> [[4]]
#> [1] 8
#>
#> [[5]]
#> [1] 10
#>
is_vowel <- function(x) {
x %in% c('a', 'e', 'i', 'o', 'u')
}
it3 <- i_drop(letters, is_vowel)
nextOr(it3, NA) # b
#> [1] "b"
nextOr(it3, NA) # c
#> [1] "c"
nextOr(it3, NA) # d
#> [1] "d"
nextOr(it3, NA) # f
#> [1] "f"
nextOr(it3, NA) # g
#> [1] "g"
# nextOr(it, NA) continues through the rest of the consonants