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

Glue inside a glue R

I would like to use a glue inside a glue. Here I created a simple reproducible example:

library(glue)
l <- c("a", "b", "c")
input = list(a = "test1",
             b = "test2",
             c = "test3")

for (i in l) {
  print(glue("{input${i}}"))
}
#> Error:
#> ! Failed to parse glue component
#> Caused by error in `parse()`:
#> ! <text>:1:7: unexpected '{'
#> 1: input${
#>           ^

Created on 2024-08-05 with reprex v2.1.0

This returns an error because we want to use a curly brace inside a curly brace. My expected output should look 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

test1
test2
test3

Because I would like the glue to look use the letters from the vector l to print the values mentioned in the list input. This is basically input$a returns test1.

So I was wondering if it is possible to use glue inside a glue in R?

>Solution :

This is classic R way of selecting columns from a dataframe (or a list in this case). Dynamically select data frame columns using $ and a character value

input[l] would give you l elements of input.

input[l]
#$a
#[1] "test1"

#$b
#[1] "test2"

#$c
#[1] "test3"

Or in the for loop use [[]] to select individual elements.

for (i in l) {
  print(glue("{input[[i]]}"))
}

#test1
#test2
#test3
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