Reputation: 1817
I have a simple question about creating custom lm functions within the tidyverse
framework.
I basically want a function that runs a custom model with me with one free variable.
model <- function(x){
lmer(paste("cyl ~", x, "+ (1|disp)"), data = .)
}
And then I want to use this in dplyr
's do
mtcars %>%
do(x = model("hp"))
How should I approach this problem?
Upvotes: 2
Views: 279
Reputation: 389285
You could pass data to the function :
library(dplyr)
library(lme4)
model <- function(data, x){
lmer(paste("cyl ~", x, "+", "(1|disp)"), data = data)
}
and then call it like :
mtcars %>% model('hp')
#Linear mixed model fit by REML ['lmerMod']
#Formula: cyl ~ hp + (1 | disp)
# Data: data
#REML criterion at convergence: 96.2
#Random effects:
# Groups Name Std.Dev.
# disp (Intercept) 0.927
# Residual 0.441
#Number of obs: 32, groups: disp, 27
#Fixed Effects:
#(Intercept) hp
# 3.1866 0.0196
Or
mtcars %>% summarise(mod = list(model(., 'hp')))
# mod
#1 <S4 class ‘lmerMod’ [package “lme4”] with 13 slots>
Upvotes: 2