Reputation: 1039
I'm after a more elegant tidyverse equivalent for [()
that works for piping and in chains of pipes. I'm tempted to just wrap around it with my own function, because I ideally want all the functionality for it (working for different datatypes, matrices, vectors, dataframes etc).
piped_subset <- function(x, ...) `[`(x, ...)
So for example, using this function, the following operations all work.
mat <- matrix(1:25, nrow = 5)
vec <- LETTERS[1:25]
df <- ToothGrowth
l <- list(vec)
mat %>% piped_subset(1, 2)
vec %>% piped_subset(24)
df %>% piped_subset(1, 2)
l %>% piped_subset(1) #not very useful here, but works.
But I'd be happier if there was a solution out there in one of the common packages, so I'm doing something a little more standard. Any ideas?
subset()
but for the selection of rows you have to use a logical (and I'm not sure how to access row numbers), so mat %>% subset(1, 2)
doesn't work.filter()
and select()
, but it takes two steps with them, and it doesn't work on matrices.pluck()
and purr()
from dplyr
but they do too little. So you have to chain a few together. Plus they don't work on matrices (well pluck does, but not in a useful way).`[`()
but that's just ugly.Upvotes: 1
Views: 401
Reputation: 47310
%>% `[`(...)
is the same thing as %>% `[`(., ...)
using an explicit dot, and the latter is strictly equivalent to %>% .[...]
after parsing. So you can simply use %>% .[...]
:
library(magrittr)
iris %>%
.[1:2,] %>%
.[,4:5]
#> Petal.Width Species
#> 1 0.2 setosa
#> 2 0.2 setosa
mat <- matrix(1:25, nrow = 5)
vec <- LETTERS[1:25]
df <- ToothGrowth
l <- list(vec)
mat %>% .[1,2]
#> [1] 6
vec %>% .[24]
#> [1] "X"
df %>% .[1,2]
#> [1] VC
#> Levels: OJ VC
l %>% .[1]
#> [[1]]
#> [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#> [20] "T" "U" "V" "W" "X" "Y"
Created on 2022-11-24 with reprex v2.0.2
Upvotes: 2
Reputation: 12819
There is magrittr::extract
, the source code of which is just extract <- `[`
(Not to be confused with tidyr::extract
, so a note of caution in case tidyr
is loaded)
From help(extract, magrittr)
:
magrittr provides a series of aliases which can be more pleasant to use when composing chains using the %>% operator.
Upvotes: 2