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>
当前内容版权归 cookbook-r.com 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cookbook-r.com .