How do I collapse a multi-column data.frame into a single text string capturing information row by row?

The goal is to take some plot data and then put the latest points in the caption as a string.

My toy data is:

df <- data.frame (state=c("buy", "sell"), freq=c(0.102, .801))

so it looks like this:

> df
  state  freq
1   buy 0.102
2  sell 0.801

I want to get the string:

mystring <- "buy 10.2%, sell 80.1%"  

So I want first row state1 with freq1 then second row state2 with freq2.

I have tried unlisting and paste with collapse but no luck yet. Apart from looping over every row is there a smarter dplyr/tidyverse way?

>Solution :


str_glue_data(df, "{state} {freq*100}%") |>
# [1] "buy 10.2%, sell 80.1%"

Leave a Reply