Last active
July 19, 2017 14:30
-
-
Save lorenzwalthert/c87685c22ddab7b9821d85fcab4ec934 to your computer and use it in GitHub Desktop.
access the formula interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` r | |
# with a formula | |
fit_something <- function(data, formula, ...) { | |
lm(as.formula(formula), data = data, ...) | |
} | |
fit_something(mtcars, "cyl ~mpg") | |
#> | |
#> Call: | |
#> lm(formula = as.formula(formula), data = data) | |
#> | |
#> Coefficients: | |
#> (Intercept) mpg | |
#> 11.2607 -0.2525 | |
# with separate inputs for response and predictors | |
fit_something2 <- function(data, response, predictors, ...) { | |
formula <- as.formula(paste(response, " ~ ", paste(predictors, collapse = "+"))) | |
lm(formula, data = data, ...) | |
} | |
fit_something2(mtcars, "cyl", setdiff(names(mtcars), "cyl")) | |
#> | |
#> Call: | |
#> lm(formula = formula, data = data) | |
#> | |
#> Coefficients: | |
#> (Intercept) mpg disp hp drat | |
#> 12.107199 -0.004857 0.004610 0.003723 -0.427435 | |
#> wt qsec vs am gear | |
#> -0.222489 -0.187945 -0.644076 -0.500770 -0.500323 | |
#> carb | |
#> 0.179872 | |
# further arguments passed to lm via ... see ?lm | |
fit_something2(data = mtcars, response = "cyl", | |
predictors = setdiff(names(mtcars), "cyl"), | |
weights = abs(rnorm(nrow(mtcars)))) | |
#> | |
#> Call: | |
#> lm(formula = formula, data = data, weights = ..1) | |
#> | |
#> Coefficients: | |
#> (Intercept) mpg disp hp drat | |
#> 13.812036 -0.021711 -0.001586 0.003722 -0.896883 | |
#> wt qsec vs am gear | |
#> 0.549706 -0.370025 -1.096041 -1.079088 0.643830 | |
#> carb | |
#> -0.215578 | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment