'Ways to select multiple columns in base R using the native pipe |>?
What are good ways to select multiple columns of a data frame in base R using the native pipe |>? (i.e., without the tidyverse/dplyr to reduce external dependencies).
If we have the data frame
dtf <- data.frame(a = 1:3, b = 4:6, c = 7:9)
then we can select columns b and c with
> dtf[c("b", "c")]
b c
1 4 7
2 5 8
3 6 9
An elegant way to do this in the tidyverse with the native pipe is
> dtf |> dplyr::select(b, c)
b c
1 4 7
2 5 8
3 6 9
My best base R attempt with the native pipe was
> dtf |> subset(select = c("b", "c"))
b c
1 4 7
2 5 8
3 6 9
A more concise (but failed attempt) was
> dtf |> `[`(c("b", "c"))
Error: function '[' not supported in RHS call of a pipe
Are there better ways to do this that I'm missing?
Note: If you wanted only a single column and were okay with dropping into a vector, then getElement
could be used:
> dtf |> getElement("b")
[1] 4 5 6
Solution 1:[1]
Here is one way:
dtf |> (\(x) `[`(x, c("b", "c")))()
# b c
#1 4 7
#2 5 8
#3 6 9
You must use the anonymous function \(x)
and pass it as an argument to [
. Don't forget to end with the parenthesis ()
.
Solution 2:[2]
Just put brackets around:
dtf |> (`[`)(c("b", "c"))
# b c
#1 4 7
#2 5 8
#3 6 9
or call it over ::
:
dtf |> base::`[`(c("b", "c"))
# b c
#1 4 7
#2 5 8
#3 6 9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rui Barradas |
Solution 2 | GKi |