Skip to content

Instantly share code, notes, and snippets.

@kevincdurand1
Last active April 8, 2017 01:30
Show Gist options
  • Save kevincdurand1/f4d984ee6c1f63266498cbd36a331123 to your computer and use it in GitHub Desktop.
Save kevincdurand1/f4d984ee6c1f63266498cbd36a331123 to your computer and use it in GitHub Desktop.
Creating a formula from a string
# 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>
# 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment