Creating a formula from a string
Problem
You want to create a formula from a string.
Solution
It can be useful to create a formula from a string. This often occurs in functions where the formula arguments are passed in as strings.
In the most basic case, use as.formula()
:
# This returns a string:
"y ~ x1 + x2"
#> [1] "y ~ x1 + x2"
# This returns a formula:
as.formula("y ~ x1 + x2")
#> y ~ x1 + x2
#> <environment: 0x3361710>
Here is an example of how it might be used:
# These are the variable names:
measurevar <- "y"
groupvars <- c("x1","x2","x3")
# This creates the appropriate string:
paste(measurevar, paste(groupvars, collapse=" + "), sep=" ~ ")
#> [1] "y ~ x1 + x2 + x3"
# This returns the formula:
as.formula(paste(measurevar, paste(groupvars, collapse=" + "), sep=" ~ "))
#> y ~ x1 + x2 + x3
#> <environment: 0x3361710>