[英]Custom R lm function within the tidyverse?
我有一個關於在tidyverse
框架中創建自定義 lm 函數的簡單問題。
我基本上想要一個 function 與我一起運行自定義 model 和一個自由變量。
model <- function(x){
lmer(paste("cyl ~", x, "+ (1|disp)"), data = .)
}
然后我想在dplyr
do
使用它
mtcars %>%
do(x = model("hp"))
我應該如何解決這個問題?
您可以將數據傳遞給 function:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.