我有一个关于在 tidyverse
框架中创建自定义 lm 函数的简单问题。
我基本上想要一个函数,它可以通过一个自由变量与我一起运行自定义模型。
model <- function(x){
lmer(paste("cyl ~", x, "+ (1|disp)"), data = .)
}
然后我想在 dplyr
的 do
中使用它
mtcars %>%
do(x = model("hp"))
我应该如何解决这个问题?
最佳答案
您可以将数据传递给函数:
library(dplyr)
library(lme4)
model <- function(data, x){
lmer(paste("cyl ~", x, "+", "(1|disp)"), data = data)
}
然后这样调用它:
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
或者
mtcars %>% summarise(mod = list(model(., 'hp')))
# mod
#1 <S4 class ‘lmerMod’ [package “lme4”] with 13 slots>
关于r - tidyverse 中的自定义 R lm 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61435484/