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

Dynamically "gluing" with {glue}

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

>Solution :

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

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