Learn R Programming

dat (version 0.5.0)

extract: Extract elements from a vector

Description

Extract elements from an object as S4 generic function. See the examples.

Usage

extract(x, ind, ...)

# S4 method for list,`function` extract(x, ind, ...)

# S4 method for atomic,`function` extract(x, ind, ...)

# S4 method for ANY,formula extract(x, ind, ...)

# S4 method for atomicORlist,numericORintegerORlogical extract(x, ind, ...)

# S4 method for ANY,character extract(x, ind, ...)

# S4 method for data.frame,character extract(x, ind, ...)

extract2(x, ind, ...)

# S4 method for atomicORlist,numericORinteger extract2(x, ind, ...)

# S4 method for ANY,formula extract2(x, ind, ...)

# S4 method for atomicORlist,`function` extract2(x, ind, ...)

# S4 method for ANY,character extract2(x, ind, ...)

Arguments

x

(atomic | list) a vector.

ind

(function | formula | character | numeric | integer | logical) a formula is coerced into a function. For lists the function is applied to each element (and has to return a logical of length 1). For atomics a vectorized function is expected. If you supply an atomic it is used for subsetting. A character of length 1 beginning with "^" is interpreted as regular expression.

...

arguments passed to ind.

Examples

Run this code
# NOT RUN {
extract(1:15, ~ 15 %% . == 0)
extract(list(xy = 1, zy = 2), "^z")
extract(list(x = 1, z = 2), 1)
extract(list(x = 1, y = ""), is.character)

# Example: even numbers:
is.even <- function(x) (x %% 2) == 0
sum((1:10)[is.even(1:10)])
extract(1:10, ~ . %% 2 == 0) %>% sum
extract(1:10, is.even) %>% sum

# Example: factors of 15
extract(1:15, ~ 15 %% . == 0)

# Example: relative prime numbers
gcd <- function(a, b) {
  .gcd <- function(a, b) if (b == 0) a else Recall(b, a %% b)
  flatmap(a ~ b, .gcd)
}

extract(1:10, x ~ gcd(x, 10) == 1)

# Example: real prime numbers
isPrime <- function(n) {
  .isPrime <- function(n) {
    iter <- function(i) {
      if (i * i > n) TRUE
      else if (n %% i == 0 || n %% (i + 2) == 0) FALSE
      else Recall(i + 6)
    }
    if (n <= 1) FALSE
    else if (n <= 3) TRUE
    else if (n %% 2 == 0 || n %% 3 == 0) FALSE
    else iter(5)
  }
  flatmap(n, x ~ .isPrime(x))
}

extract(1:10, isPrime)
# }

Run the code above in your browser using DataLab