简体   繁体   English

tidyverse 内自定义 R lm function?

[英]Custom R lm function within the tidyverse?

I have a simple question about creating custom lm functions within the tidyverse framework.我有一个关于在tidyverse框架中创建自定义 lm 函数的简单问题。

I basically want a function that runs a custom model with me with one free variable.我基本上想要一个 function 与我一起运行自定义 model 和一个自由变量。

model <- function(x){
  lmer(paste("cyl ~", x, "+ (1|disp)"), data = .)
}

And then I want to use this in dplyr 's do然后我想在dplyr do使用它

mtcars %>% 
  do(x = model("hp"))

How should I approach this problem?我应该如何解决这个问题?

You could pass data to the function:您可以将数据传递给 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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