pick_elements | R Documentation |
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)
x |
A list, data frame, or vector. |
which |
The index or name of the element(s) to extract. |
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.
pick1()
returns a subset of x
.
pick2()
returns a single element from x
.
lst <- list(a = 1:3, b = 4:6)
# Without pipe
pick1(lst, "a") # List with one element
pick2(lst, "a") # Just the vector 1:3
# With base R pipe
lst |> pick1("a")
lst |> pick2("a")
df <- data.frame(x = 1:5, y = letters[1:5])
df |> pick1("y") # Returns a data frame with column 'y'
df |> pick2("y") # Returns column 'y' as a character vector
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.