R多模型多功能

R多模型多功能,r,tidyverse,tidyr,purrr,lme4,R,Tidyverse,Tidyr,Purrr,Lme4,我编写了一个例程,从lmer模型中提取信息,计算ICC,并从lmerTest的ranova函数中获得LRT。我下面的方法很有效,但我认为可以通过(a)将两个函数合并为一个函数并返回一个列表来改进,但我似乎无法使用purrr的map函数访问列表元素,以及(b)使用多个mutate/purrr行在一个位置获取所有需要的数据,而不必稍后进行连接。我的代码如下所示,使用Hox(2002)中提供的“Peet”数据集,可从UCLA IDRE网站获得: library(foreign) library(lme

我编写了一个例程,从lmer模型中提取信息,计算ICC,并从lmerTest的ranova函数中获得LRT。我下面的方法很有效,但我认为可以通过(a)将两个函数合并为一个函数并返回一个列表来改进,但我似乎无法使用purrr的map函数访问列表元素,以及(b)使用多个mutate/purrr行在一个位置获取所有需要的数据,而不必稍后进行连接。我的代码如下所示,使用Hox(2002)中提供的“Peet”数据集,可从UCLA IDRE网站获得:

library(foreign)
library(lme4)
library(tidyverse)
library(purrr)


#Peet family data described and used in Hox
peet.dat<-read.dta("https://stats.idre.ucla.edu/stat/stata/examples/mlm_ma_hox/peetmis.dta")

names(peet.dat)

#convert to long format
peet.long.dat <- peet.dat %>%
  tidyr::gather(type, score, -family,-sex,-person) %>%
  arrange(type)

names(peet.long.dat)

#need two functions, one for the MLM estimates and the other for
#ranova p-test for variance--merge later by type

aov_model <- function(df) {
  lmr.model <- lmerTest::lmer(score~ 1 + (1|family), data=df)
}

aov_test <- function(df) {
  lmr.model <- lmerTest::lmer(score~ 1 + (1|family), data=df)
  ll.test <- lmerTest::ranova(lmr.model)
}

#get the model estimates
models <- peet.long.dat %>%
  nest(-type) %>%
  mutate(aov_obj = map(data, aov_model),
         summaries = map(aov_obj, broom.mixed::tidy)) %>%
  unnest(summaries, .drop = T) %>%
  select(type, effect, estimate, term) %>%
  filter(effect != "fixed") %>%
  mutate(variance = estimate^2) %>%
  select(-estimate, -effect) %>%
  spread(term, variance) %>%
  rename(group.var = `sd__(Intercept)`, residual = `sd__Observation`) %>%
  mutate(ICC = group.var/(group.var+residual))


models

#get the ranova LRTs
tests <- peet.long.dat %>%
  nest(-type) %>%
  mutate(test_obj = map(data, aov_test),
         test_summaries = map(test_obj, broom.mixed::tidy)) %>%
  unnest(test_summaries, .drop = T) %>%
  filter(!is.na(LRT))

#join estimates with LRT p values
models %>% left_join(tests[c("type","p.value")])
库(外文)
图书馆(lme4)
图书馆(tidyverse)
图书馆(purrr)
#Hox中描述和使用的Peet系列数据
peet.dat%
排列(类型)
名称(peet.long.dat)
#需要两个功能,一个用于传销估算,另一个用于
#方差的ranova p检验——稍后按类型合并
aov_模型%
变异(方差=估计值^2)%>%
选择(-estimate,-effect)%>%
价差(期限、差异)%>%
重命名(group.var=`sd\uuu(Intercept)`,resident=`sd\uu Observation`)%>%
突变(ICC=组变量/(组变量+残差))
模型
#去拉诺瓦轻轨
测试%
嵌套(-type)%%>%
变异(测试对象=地图(数据,aov测试),
测试摘要=地图(测试对象,扫帚混合::整齐))%>%
未测试(测试摘要,.drop=T)%>%
过滤器(!is.na(LRT))
#将估算值与LRT p值连接起来
模型%>%左联合(测试[c(“类型”,“p.value”)]))
非常感谢您的帮助