Home > Blockchain >  Dynamically "gluing" with {glue}
Dynamically "gluing" with {glue}

Time:11-23

Is there any way to supply a vector to {glue} to dynamically choose which columns get "glued"? desired here is what would I am hoping to see but I just want to be able to provide vars to a glue statement.

library(glue)
library(dplyr)

vars <- c("Sepal.Length", "Species")

iris %>%
  head() %>% ## just for less data
  # mutate(glue_string = glue_data("{vars}")) %>%
  mutate(desired = glue("{Sepal.Length}{Species}"))

#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species   desired
#> 1          5.1         3.5          1.4         0.2  setosa 5.1setosa
#> 2          4.9         3.0          1.4         0.2  setosa 4.9setosa
#> 3          4.7         3.2          1.3         0.2  setosa 4.7setosa
#> 4          4.6         3.1          1.5         0.2  setosa 4.6setosa
#> 5          5.0         3.6          1.4         0.2  setosa   5setosa
#> 6          5.4         3.9          1.7         0.4  setosa 5.4setosa

CodePudding user response:

We may either use .data to extract the column from each element of 'vars' and glue it

library(dplyr)
library(glue)
iris %>%
   head() %>% ## just for less data
     mutate(desired = glue("{.data[[vars[1]]]}{.data[[vars[2]]]}"))

-output

Sepal.Length Sepal.Width Petal.Length Petal.Width Species   desired
1          5.1         3.5          1.4         0.2  setosa 5.1setosa
2          4.9         3.0          1.4         0.2  setosa 4.9setosa
3          4.7         3.2          1.3         0.2  setosa 4.7setosa
4          4.6         3.1          1.5         0.2  setosa 4.6setosa
5          5.0         3.6          1.4         0.2  setosa   5setosa
6          5.4         3.9          1.7         0.4  setosa 5.4setosa

Or loop across all_of the elements in 'vars' to subset the data, invoke str_c to paste the columns by row

library(stringr)
library(purrr)
iris %>%
  head() %>% ## just for less data
    mutate(desired = invoke(str_c, across(all_of(vars))))
  • Related