Search code examples
rdplyrmacrosacross

Want to cycle through dataframe rows and columns using the names and values to run a simple macro generator


I'm using R to build a simple macro generator, and I want to map across a data frame making substitutions in a string building one output string for each row of the dataframe

library(tidyverse)

df<-tribble(
  ~title, ~name,~age,
  "Mr","Smith",46,
  "Ms","Jones",26,
  "Ms","Wiles",20
)

str<-"
This has parameters {{title}} {{name}}
and more {{age}}
"

I need to apply a gsub function for each row of the dataframe and sub the values for parameter names matching the column

fun<-function(name-of-column,value-of-column) {
    gsub("\\{name-of-column\\}",value-in-column,str)
}

It's easy to permute the column data

df %>% mutate(across(where(is.character),~ gsub("mit","yyy",.x)))

But I want to operate on something outside and pass the name and value of the column to the operation .x gives the value in the tibble but how do a refer to the name?

df %>% mutate(across(where(is.character),~ fun(.x,.x)))

I hope that makes sense!


Solution

  • If I understand you correctly, i.e. creating a string for each row of your data based on the str pattern, you could use glue::glue to achieve your desired result like so:

    library(tidyverse)
    
    df <- tribble(
      ~title, ~name, ~age,
      "Mr", "Smith", 46,
      "Ms", "Jones", 26,
      "Ms", "Wiles", 20
    )
    
    str <- "
    This has parameters {{title}} {{name}}
    and more {{age}}
    "
    
    df %>%
      mutate(
        output = glue::glue(str, .open = "{{", .close = "}}")
      )
    #> # A tibble: 3 × 4
    #>   title name    age output                                    
    #>   <chr> <chr> <dbl> <glue>                                 
    #> 1 Mr    Smith    46 This has parameters Mr Smith
    #> and more 46
    #> 2 Ms    Jones    26 This has parameters Ms Jones
    #> and more 26
    #> 3 Ms    Wiles    20 This has parameters Ms Wiles
    #> and more 20