Introduction to Writing Functions in R
Richie Cotton
Data Evangelist at DataCamp
select()
selects columns
filter()
filters rows
A better name would be run_linear_regression()
h <- head
data(cats, package = "MASS")
h(cats)
Sex Bwt Hwt
1 F 2.0 7.0
2 F 2.0 7.4
3 F 2.0 9.5
4 F 2.1 7.2
5 F 2.1 7.3
6 F 2.1 7.6
args(lm)
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
args(cor)
function (x, y = NULL, use = "everything",
method = c("pearson", "kendall", "spearman"))
This won't work
data %>%
lm(formula)
because the data argument isn't first.
run_linear_regression <- function(data, formula) {
lm(formula, data)
}
cats %>%
run_linear_regression(Hwt ~ Bet + Sex)
Call:
lm(formula = formula, data = data)
Coefficients:
(Intercept) Bwt SexM
-0.4150 4.0758 -0.0821
Introduction to Writing Functions in R