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():

  1. # This returns a string:
  2. "y ~ x1 + x2"
  3. #> [1] "y ~ x1 + x2"
  4. # This returns a formula:
  5. as.formula("y ~ x1 + x2")
  6. #> y ~ x1 + x2
  7. #> <environment: 0x3361710>

Here is an example of how it might be used:

  1. # These are the variable names:
  2. measurevar <- "y"
  3. groupvars <- c("x1","x2","x3")
  4. # This creates the appropriate string:
  5. paste(measurevar, paste(groupvars, collapse=" + "), sep=" ~ ")
  6. #> [1] "y ~ x1 + x2 + x3"
  7. # This returns the formula:
  8. as.formula(paste(measurevar, paste(groupvars, collapse=" + "), sep=" ~ "))
  9. #> y ~ x1 + x2 + x3
  10. #> <environment: 0x3361710>