I'm looking to do string interpolation with R's glue::glue()
on a vector, without calling it multiple times.
Example:
df <- data.frame(x = 1:10)
glue::glue("No. of Rows: {dim(df)[1]}, No. of Columns: {dim(df)[2]}")
Would give as required:
No. of Rows: 10, No. of Columns: 1
But I'm calling dim(df)
twice, where it is a vector of length 2.
I was wondering if glue
can handle this similar to string interpolation in Python with the % operator:
import pandas as pd
df = pd.DataFrame({"x": range(10)})
print('No. of Rows: %d, No. of Columns: %d' % df.shape)
Which gives the same required output without calling df.shape
twice.
Yes, you can do this:
glue("nr = {x[1]}, nc = {x[2]}", x = dim(mtcars))
# nr = 32, nc = 11
From the ?glue
documentation, the description of ...
is:
Unnamed arguments are taken to be expressions string(s) to format. Multiple inputs are concatenated together before formatting. Named arguments are taken to be temporary variables available for substitution.
(Emphasis mine, highlighting the part relevant to this question.)