1

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.

Giora Simchoni
  • 3,487
  • 3
  • 34
  • 72

3 Answers3

4

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.)

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
3

You could use this, similar to Python's f-string interpolation:

shape <- dim(df)
glue::glue("No. of Rows: {shape[1]}, No. of Columns: {shape[2]}")
tdy
  • 36,675
  • 19
  • 86
  • 83
0

I'm not sure if you can do it natively, but one thing you could do would be to wrap it in a function:

f <- function(x) glue::glue("No. of Rows: {x[1]}, No. of Columns: {x[2]}")

f(dim(df))
Matt Kaye
  • 521
  • 4
  • 5