Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pipe the columns of a dataframe directly into a function?

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 = ", ")
like image 921
luciano Avatar asked Dec 06 '25 05:12

luciano


1 Answers

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 =", ")
like image 57
Ben Bolker Avatar answered Dec 07 '25 18:12

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!