ewenharrison / finalfit
1
#' Mixed effects linear regression models: \code{finalfit} model wrapper
2
#'
3
#' Using \code{finalfit} conventions, produces mixed effects linear regression
4
#' models for a set of explanatory variables against a continuous dependent.
5
#'
6
#' Uses \code{lme4::\link[lme4]{lmer}} with \code{finalfit} modelling
7
#' conventions. Output can be passed to \code{\link{fit2df}}. This is only
8
#' currently set-up to take a single random effect as a random intercept. Can be
9
#' updated in future to allow multiple random intercepts, random gradients and
10
#' interactions on random effects if there is a need.
11
#'
12
#' @param .data Dataframe.
13
#' @param dependent Character vector of length 1, name of depdendent variable
14
#'   (must be continuous vector).
15
#' @param explanatory Character vector of any length: name(s) of explanatory
16
#'   variables.
17
#' @param random_effect Character vector of length 1, either, (1) name of random
18
#'   intercept variable, e.g. "var1", (automatically convered to "(1 | var1)");
19
#'   or, (2) the full \code{lme4} specification, e.g. "(var1 | var2)". Note
20
#'   parenthesis MUST be included in (2)2 but NOT included in (1).
21
#' @param ... Other arguments to pass to \code{lme4::\link[lme4]{lmer}}.
22
#' @return A list of multivariable \code{lme4::\link[lme4]{lmer}} fitted model
23
#'   outputs. Output is of class \code{lmerMod}.
24
#'
25
#' @seealso \code{\link{fit2df}}
26
#' @family finalfit model wrappers
27
#' @export
28
#'
29
#' @examples
30
#' library(finalfit)
31
#' library(dplyr)
32
#'
33
#' explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
34
#' random_effect = "hospital"
35
#' dependent = "nodes"
36
#'
37
#' colon_s %>%
38
#'   lmmixed(dependent, explanatory, random_effect) %>%
39
#' 	 fit2df(estimate_suffix=" (multilevel")
40

41
lmmixed <- function(.data, dependent, explanatory, random_effect, ...){
42
	# If single term random effect, default to random intercept model
43 1
	if(!grepl("\\|", random_effect)) random_effect = paste0("(1 | ", random_effect, ")")
44 1
  lme4::lmer(paste0(dependent, "~", paste(explanatory, collapse="+"), " + ", random_effect),
45 1
             data = .data, ...)
46
}

Read our documentation on viewing source code .

Loading