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