Convert string expression to function
stm_function.Rd
stm_function()
converts a function or string representation of an
expression into a valid R function. Checks variable compatibility and
provides warnings or errors as necessary.
Arguments
- fexpr
A function or string representing a mathematical expression. Strings must represent valid mathematical expressions.
- vars
Optional. A character vector of expected variable names. Default is
NULL
meaning that variables will be assumed for multi-variable expressions.- nvars
Optional. An integer specifying the expected number of variables in the expression. Raises an error if the count differs. Default is
NULL
- par_name
Optional. A string used in error and warning messages to refer to the parameter. Defaults is
"fexpr"
.
Value
If fexpr
is a function, it is returned unchanged. If it is
a string, a callable R function is constructed and returned.
Details
The function checks whether fexpr
is a valid function or expression.
If it is a string, variables are identified and a callable function is
constructed. If nvars
is specified and does not match the variable
count, an error is raised. If vars
is not specified and multiple
variables are found, a warning is issued and default names are assumed.
See also
stm_function
, stm_fexpr_vars
Examples
f <- stm_function(
fexpr = "2 * x + sqrt(y) + cos(a) / pi",
vars = c("x", "y", "a")
)
f(3, 4, 5)
#> [1] 8.090292
f(x = 3, y = 4, a = 5)
#> [1] 8.090292
f(a = 3, x = 4, y = 5)
#> [1] 9.920944