Skip to contents

Extract vectors by index or value occurrence

Extract front by first occurrence of a value %[f%

Extract front by last occurrence of a value %[l%

Extract vector front by index %[%

Extract vector rear by index %]%

Extract first occurrence of a value to vector rear %f]%

Extract last occurrence of a value to vector rear %l]%

Extract values at percentile and higher %q]%

Extract values higher than percentile %q)%

Extract values at percentile and smaller %[q%

Extract values smaller than percentile %(q%

Extract first, middle or last value of vector %:%

Usage

x %[f% v

x %[l% v

x %[% i

x %]% i

x %f]% v

x %l]% v

x %q]% q

x %q)% q

x %[q% q

x %(q% q

x %:% j

Arguments

x

A vector

v

A value of which the first or last occurrence in x will be used as an index

i

An index or two element vector c(lo,hi) indicating a range to extract

q

A percentile value (between 0 and 1)

j

A character indicating to extract the first f, middle m or last l value of x.

Value

A vector extracted from the front, rear, or, range of x. Either based on an index or the first or last occurrence of a value or the first, middle, or, last element of a vector.

Note

The function provided for symmetry, character lengths of x%]%i and x[1:i] are equal.

Examples


z <- letters

# Extract front by first occurrence of value
z %[f% "n"
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"

# Extract front by index
x <- rnorm(100)
x %[% 10
#>  [1] -1.400043517  0.255317055 -2.437263611 -0.005571287  0.621552721
#>  [6]  1.148411606 -1.821817661 -0.247325302 -0.244199607 -0.282705449

# Extract rear by index
x %]% 90
#>  [1] -0.38195111  0.42418757  1.06310200  1.04871262 -0.03810289  0.48614892
#>  [7]  1.67288261 -0.35436116  0.94634789  1.31682636 -0.29664002

# Extract rear by index
x %]% 90
#>  [1] -0.38195111  0.42418757  1.06310200  1.04871262 -0.03810289  0.48614892
#>  [7]  1.67288261 -0.35436116  0.94634789  1.31682636 -0.29664002

# Extract by indices if a range is provided
x %]% c(4,30)
#>  [1] -0.005571287  0.621552721  1.148411606 -1.821817661 -0.247325302
#>  [6] -0.244199607 -0.282705449 -0.553699384  0.628982042  2.065024895
#> [11] -1.630989402  0.512426950 -1.863011492 -0.522012515 -0.052601910
#> [16]  0.542996343 -0.914074827  0.468154420  0.362951256 -1.304543545
#> [21]  0.737776321  1.888504929 -0.097445104 -0.935847354 -0.015950311
#> [26] -0.826788954 -1.512399651
z %[% c(6,10)
#> [1] "f" "g" "h" "i" "j"

# Extract last/middle value of x
x %:% "l"
#> [1] -0.29664
z %:% "m"
#> [1] "m"

# Extract by percentile
seq(1,10,.5) %(q% .5 # infix
#> [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
seq(1,10,.5)[seq(1,10,.5) < quantile(seq(1,10,.5),.5)] # regular syntax
#> [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

seq(1,10,.5) %q]% .5 # infix
#>  [1]  5.5  6.0  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0
seq(1,10,.5)[seq(1,10,.5) >= quantile(seq(1,10,.5),.5)] # regular syntax
#>  [1]  5.5  6.0  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0