Search code examples
rdataframepipetibble

How can I run a function at the end of a pipe?


This code makes a sentence from two different columns in a data frame

library(dplyr); library(tibble); library(magrittr)

mtcars %>% 
  rownames_to_column(var = "car") %>%
  sample_n(5) -> 
  df

paste0(df$car, " (", df$mpg, ")", collapse = ", ")

# "Mazda RX4 Wag (21), Hornet Sportabout (18.7), Merc 280 (19.2), Dodge Challenger (15.5), Merc 450SLC (15.2)"

But instead of having paste0(df$car, " (", df$mpg, ")", collapse = ", ") run on a standalone line, how can I get it to run at end of pipe like the below (which throws an error as written):

mtcars %>% 
  rownames_to_column(var = "car") %>%
  sample_n(5) %>%
  paste0(df$car, " (", df$mpg, ")", collapse = ", ")

Solution

  • with() would work for this:

    mtcars %>% 
      rownames_to_column(var = "car") %>%
      sample_n(5) %>% 
      with(paste0(car, " (", mpg, ")", collapse = ","))
    

    Another possibility would be to end the pipe with:

    ... %>% 
       mutate(word = glue("{car} ({mpg})")) %>% 
       pull(word) %>% 
       paste0(collapse =", ")