Search code examples
rmagrittr

How to call an element of an object created with a magrittr pipe?


Using the magrittr piper operator we perform manipulation on a vector.

strings <- "a b c"
strings %>% strsplit(" ") # Here we get a list 


> strings %>% strsplit(" ")
[[1]]
[1] "a" "b" "c"

But let's assume that we would only like to get the single element of this list. This would require us to (example to get the first element):

(strings %>% strsplit(" "))[[1]][1] # Notice the braces around the expression.. 

Now to my question: Is there a way to use the pipe operator without the need of putting the whole expression in braces? It would be more transparent, I think, if we would not have to write it into a temporary variable or use brackets but use some kind of a special pipe operator.

Is there another way to do this?


Solution

  • Or also:

    strings %>% strsplit(" ") %>% { .[[1]][1] }

    which would be the same as

    strings %>% strsplit(" ") %>% .[[1]] %>% .[1]

    Compare the timings:

    library(purrr)
    library(dplyr)
    microbenchmark::microbenchmark(
      (strings %>% strsplit(" ") %>%  unlist %>%  first)
      ,(strings %>%  strsplit(" ") %>% { .[[1]][1] })
      ,(strings %>% strsplit(" ") %>% map_chr(1))
    )
    # Unit: microseconds
    #                                          expr     min      lq       mean     median       uq      max    neval
    # (strings %>% strsplit(" ") %>% unlist %>% first)   280.270 288.363  301.9581 295.4685 305.1395  442.511   100
    # (strings %>% strsplit(" ") %>% {     .[[1]][1] })  211.980 219.875  229.4866 226.3875 235.6640  298.429   100
    # (strings %>% strsplit(" ") %>% map_chr(1))         682.123 693.965 747.1690 710.1495 752.3875  2578.091   100