Extract (pick) elements without using brackets so that elements can be picked out as part of a pipe workflow.
pick1(x, which)
pick2(x, which)pick1() returns a subset of x.
pick2() returns a single element from x.
These two helper functions extract elements from lists, data frames, or vectors. They are simple wrappers for the standard bracket operators in R:
pick1() uses single brackets ([) and returns a subset.
pick2() uses double brackets ([[) and returns the element itself.
These are safer and more flexible than $, especially when used with the base R pipe (|>)
or in functional programming.
lst <- list(a = 1:3, b = 4:6)
# Without pipe
pick1(lst, "a")      # List with one element
#> $a
#> [1] 1 2 3
#> 
pick2(lst, "a")      # Just the vector 1:3
#> [1] 1 2 3
# With base R pipe
lst |> pick1("a")
#> $a
#> [1] 1 2 3
#> 
lst |> pick2("a")
#> [1] 1 2 3
df <- data.frame(x = 1:5, y = letters[1:5])
df |> pick1("y")     # Returns a data frame with column 'y'
#>   y
#> 1 a
#> 2 b
#> 3 c
#> 4 d
#> 5 e
df |> pick2("y")     # Returns column 'y' as a character vector
#> [1] "a" "b" "c" "d" "e"