Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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 :

library(stringr)

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading