Sometimes you want to do the following:
You have a dataset, such as the following data about individuals and their current living region in Finland:
# A tibble: 100 x 3
id state height
<chr> <chr> <dbl>
1 id_940 Uusimaa 175.
2 id_479 Lapland 160.
3 id_797 Uusimaa 151.
4 id_525 Uusimaa 173.
5 id_499 Ostrobothnia 169.
6 id_688 Uusimaa 154.
7 id_389 South Karelia 158.
8 id_366 South Karelia 160.
9 id_742 Uusimaa 166.
10 id_298 Lapland 172.
# … with 90 more rows
And you would like to make a statement in an R markdown file as follows:
```{r}
states <- "Ostrobothnia, Uusimaa, South Karelia and Lapland"
```
The study participants were from four different Finnish states:
`r states`.
so it produces:
The study participants were from four different Finnish states: Ostrobothnia, Uusimaa, South Karelia and Lapland.
During the course of a data analysis, we want to store out data or data visualizations using the same basename experiment-2020-07-13:
## save a plot
ggsave("/data/plots/experiment-2020-07-13.pdf")
## save data
write_tsv(data, path = "/data/tables/experiment-2020-07-13.tsv")Instead of repetition, it would be handy if we could do the following:
To tackle these two problems, we need a solution that can combine numbers and characters into strings.
This is some text + NUMBER + TEXT.
For example, if we define SUN and SNOW, then
SUN = 50
SNOW = 3
"This year, South of Finland had on average" +
SUN + "days of sunshine and" +
SNOW + "of days snowfall."
results in
This year, South of Finland had on average
50 days of sunshine and 3 of days snowfall.
The R package glue does exactly that.
Here is an example:
sun <- 50
snow <- 3
glue("This year, South of Finland had on average {sun}
days of sunshine and {snow} of days snowfall.")This year, South of Finland had on average 50
days of sunshine and 3 of days snowfall.
If you have used the function paste before, then think of glue as the tidyverse answer to paste.
Explore all functions:
[1] "as_glue" "glue" "glue_col" "glue_collapse"
[5] "glue_data" "glue_data_col" "glue_data_safe" "glue_data_sql"
[9] "glue_safe" "glue_sql"
We are going to use glue and glue_collapse.
Glue one element (animals).
There were Elephants.
Glue two elements.
There were 3 Elephants.
Glue two elements, but define them within the glue command.
There were 2 Giraffes.
Tweak the following R command so that it returns: Yesterdays average temperature was 20.2 celsius.
Collapse the elements in a vector
FTOAPOEPCSK9
Collapse the elements and separate them with a +.
FTO + APOE + PCSK9
Predict the output of the following R code and choose solution 1, 2, 3 or 4 below.
pine,firandcedar
pine, fir and cedarpine,firandcedarpine,fir,cedarpine + fir + cedar```{r}
states <- c("Ostrobothnia", "Uusimaa", "South Karelia", "Lapland")
```
The study participants were from four different Finnish states:
`r glue_collapse(states, sep = ", ", last = " and ")`.
stringr cheatsheet