Home > Mobile >  Replace template text with given vector of strings in R
Replace template text with given vector of strings in R

Time:11-06

I have a .txt file which contains an invitation template, where certain values have to be replaced by strings in a given vector.

The text looks like this:

Dear ,''''we are happy to invite you to our annual showroom . The event starts on at in , .''We look forward to your visist.'

Now I need to write a function with the template text and the vector which replaces these placeholders with given values and return the new invitation. the result should look like this

Dear Mr. George Clooney , we are happy to invite you to our annual showroom 2022. The event starts on 01.04 at 10.00h in Headquarter Office, Mainroad 26, 4711 Ytown. 

As of now i opened the textfile and initiated the function and declared. The head of the function looks like this:

createLetter <- function(fieldsdata, templateText){
    x <- c(fieldsdata)
}

CodePudding user response:

If your placeholder is e.g. "X" this is one approach

Data

st_0 <- c("Dear X , we are happy to invite you to our annual showroom X . The event starts on X at X in X . We look forward to your visit.")
repl <- c("Mr. George Clooney", "2022", "01.04", "10.00h", "Headquarter Office, Mainroad 26, 4711 Ytown")

Function

Split string into words, get locations of placeholder and replace with fields. Finally join words back together.

insert <- function(text, fields){
  st <- strsplit(text, " ")[[1]]
  st[st == "X"] <- fields
  paste(st, collapse=" ")
}

Use function (and remove spaces before . and , with gsub).

gsub(" ([,\\.])", "\\1", insert(st_0, repl))
[1] "Dear Mr. George Clooney, we are happy to invite you to our annual showroom 2022. The event starts on 01.04 at 10.00h in Headquarter Office, Mainroad 26, 4711 Ytown. We look forward to your visit."

CodePudding user response:

My initial thinking is that you want to leverage glue here:

template <- "Dear {title} {name}, we are happy to invite you to our annual showroom {year}. The event starts on {date} at {time} in {location}. We look forward to your visist."

createLetter <- function(templateText, ...){
    glue::glue(templateText, ...)
}

createLetter(template, 
             title = "Mr.", 
             name = "George Clooney",
             year = "2022",
             date = "01.04",
             time = "10.00h",
             location = "Headquarter Office, Mainroad 26, 4711 Ytown")
#> Dear Mr. George Clooney, we are happy to invite you to our annual showroom 2022. The event starts on 01.04 at 10.00h in Headquarter Office, Mainroad 26, 4711 Ytown. We look forward to your visist.
  • Related