5

I am attempting to exclusively use piping to rewrite the following code (using babynames data from babynames package:

library(babynames)
library(dplyr)

myDF <- babynames %>% 
group_by(year) %>% 
summarise(totalBirthsPerYear = sum(n))

slice(myDF, seq(1, nrow(myDF), by = 20))

The closest I have gotten is this code (not working):

myDF <- babyNames %>% 
group_by(year) %>% 
summarise(totalBirthsPerYear = sum(n)) %>% 
slice( XXX, seq(1, nrow(XXX), by = 20))

where XXX is meant to be passed via pipes to slice, but I'm stuck. Any help is appreciated.

Andrew Jackson
  • 823
  • 1
  • 11
  • 23
user7988855
  • 95
  • 1
  • 3
  • 1
    The last line should be `slice(seq(1, nrow(.), by = 20))`. You don't need the first `XXX` because the output of `summarise` is already automatically piped into `slice`. The second `XXX` is replaced by `.`, where `.` is the "pronoun" used to refer to the data frame that was piped into the function. – eipi10 May 10 '17 at 00:08
  • spectacular, thanks so much! – user7988855 May 10 '17 at 03:02

2 Answers2

10

You can reference piped data in a different position in the function by using the . In your case:

myDF2 <- babynames %>%
    group_by(year) %>%
    summarize(totalBirthsPerYear = sum(n)) %>%
    slice(seq(1, nrow(.), by = 20))
Andrew Jackson
  • 823
  • 1
  • 11
  • 23
8

Not sure if this should be opened as a separate question & answer but in case anybody arrives here as I did looking for the answer to the MULTIPLE in the title: R: Using piping to pass a single argument to multiple locations in a function

Using the . from Andrew's answer in multiple places also achieves this.

[example] To get the last element of a vector vec <- c("first", "middle", "last") we could use this code.

vec[length(vec)]

Using piping, the following code achieves the same thing:

vec %>% .[length(.)] 

Hopefully this is helpful to others as it would have helped me (I knew about the . but couldn't get it working in multiple locations).

Dave
  • 410
  • 6
  • 13
  • It doesn't work for me in this example: `vec %>% lead(., 0) + lead(., 1)`. I get `Error in vec_size(x) : object '.' not found` – Caspar V. Sep 06 '22 at 14:51