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

Time:11-25

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?

  • I'm aware of 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.
  • I'm aware of filter() and select(), but it takes two steps with them, and it doesn't work on matrices.
  • I'm aware of 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).
  • I'm aware that I can use "[()" but that's just ugly.

CodePudding user response:

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.

  • Related