Josh White
Josh White

Reputation: 1039

Is there a good tidyverse equivalent of `[()` for subsetting within a pipe?

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?

Upvotes: 1

Views: 401

Answers (2)

moodymudskipper
moodymudskipper

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

Aur&#232;le
Aur&#232;le

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

Related Questions