Learn R Programming

kardl (version 0.1.1)

replaceValues: Replace Patterns with Evaluated Values

Description

The replaceValues() function allows you to replace placeholders in text with variable values or evaluated expressions. Placeholders are marked by {} brackets, and the function supports capturing both global and non-global variables, making it useful for templating and dynamic string generation in R.

Usage

replaceValues(original_text, x = FALSE, capture_warnings = TRUE)

Value

A string with all placeholders replaced by evaluated values.

Arguments

original_text

A string containing expressions within {} to be evaluated and replaced.

x

Non-global variables to be evaluated within the function's context.

capture_warnings

Logical. If TRUE, captures errors and warnings during evaluation and continues with replacements. If FALSE, errors and warnings are not captured.

See Also

Examples

Run this code

 # Basic example with global variables
orjTXT <- "My F value is {thisF} and  its criterion is {CrF}"
thisF <- 2.33
CrF <- 32.43
replaceValues(orjTXT)
cat(replaceValues("The summary ls: {summary(lm(mpg ~ wt + hp, data = mtcars))}\n This is example"))

 # Nested function example for non-global variables
globalY <- 10
bb <- function(x){
  y <-  x+2;
 secondFunc <- function(x){
   replaceValues("The global value of Y+3 is {globalY+3}.  The non global value is {x}",x)
  }
  secondFunc(y)
}
bb(5)


 # Nested variables example. Something like $$ in PHP
FirstVar <- "First"
SecondVar <- "Second"
FirstSecondVar <- "_____________"
orjTXT <- "First var is {FirstVar}. The combinations of var names \"FirstSecondVar\" "
orjTXT <- paste0(orjTXT,"is= {{FirstVar}{SecondVar}Var}. Where SecondVar = {SecondVar} .")
replaceValues( orjTXT)

# Using mathematical expressions
MyVar = 3
replaceValues( "First var multiplying to 12 is {MyVar*12} and its power is {MyVar^12}.")

# Using templates from external files
# file_contents <- readLines(system.file("template", templateName, package = getPackageName()))
file_contents <- readLines(system.file("template", "printkardl.txt", package = "kardl"))
data(imf_example_data)
 MyFormula<-CPI~ER+PPI+asym(ER)+deterministic(covid)+trend
 kardl_model<-kardl(imf_example_data,MyFormula,mode="quick")
output<- replaceValues(file_contents,kardl_model)
cat(output)

Run the code above in your browser using DataLab