简体   繁体   中英

Custom R lm function within the tidyverse?

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM