2

I've just come across the pull() function and the output is somehow different when using it in a pipeline. See this example:

## What's the problem with pull()?
##
install.packages("hflights")
library(hflights)
library(magrittr)

## Here we create two vectors
##
origins <- pull(hflights, Origin)
destinations <- pull(hflights, Dest)

## Here we combine them into one vector and retrieve the unique values:
##

c(origins, destinations) %>% unique()

## So what's the problem with this?:
## It returns a nested list.

hflights %>% c(pull(.,Origin), pull(.,Dest)) %>% unique()
Maël
  • 45,206
  • 3
  • 29
  • 67
Charles Knell
  • 117
  • 1
  • 9
  • Instead of using two `pull`s, `select` the columns of interest and `unlist` or `flatten` i.e. `hflights %>% select(Origin, Dest) %>% flatten_chr %>% unique` or `hflights %>% select(Origin, Dest) %>% invoke(c, .) %>% unique` – akrun Sep 05 '22 at 16:12
  • R also has a dedication function for `unique(c(x, y))` which is `union()`: `do.call(union, hflights[c('Origin', 'Dest')] |> unname())` – s_baldur Sep 05 '22 at 16:25
  • While these are perfectly fine alternatives, my interest was in why I couldn't c() the vectors returned from pull() in the usual way. Like Perl, with R "there's more than one way to do it." – Charles Knell Sep 06 '22 at 17:13

1 Answers1

2

you will get your expected result by using curly braces around the complex middle section

hflights %>% {c(pull(.,Origin), pull(.,Dest)) }%>% unique()
Nir Graham
  • 2,567
  • 2
  • 6
  • 10
  • I wonder why, any hint? – Maël Sep 05 '22 at 16:04
  • That certainly does work, but I second Mael's question. What's special about enclosing that part in curly braces? – Charles Knell Sep 05 '22 at 16:10
  • 1
    The docs say `Each rhs is essentially a one-expression body of a unary function. Therefore defining lambdas in magrittr is very natural, and as the definitions of regular functions: if more than a single expression is needed one encloses the body in a pair of braces, { rhs }. However, note that within braces there are no "first-argument rule": it will be exactly like writing a unary function where the argument name is "." (the dot).` – Nir Graham Sep 05 '22 at 16:14
  • 1
    @CharlesKnell https://stackoverflow.com/questions/42385010/using-the-pipe-and-dot-notation/42386886 also gives a good explanation – Martin C. Arnold Sep 05 '22 at 16:25