Построение случайных эффектов для биномиального GLMER в ggplot - PullRequest
0 голосов
/ 12 ноября 2018

Я использовал ggplot2 для построения биномиальных подгонок для данных о выживаемости (1,0) с непрерывным предиктором, использующим geom_smooth(method="glm"), но я не знаю, возможно ли включить случайный эффект, используя geom_smooth(method="glmer") , При попытке получить следующее предупреждающее сообщение:

Предупреждающее сообщение: Вычисление не удалось в stat_smooth(): Термины случайных эффектов не указаны в формуле

Возможны ли конкретные случайные эффекты в stat_smooth(), и если да, то как это сделать?

ggplot GLM

Пример кода и фиктивные данные ниже:

library(ggplot2)
library(lme4)

# simulate dummy dataframe

x <- data.frame(time = c(1, 1, 1, 1, 1, 1,1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                         3, 3, 3, 3, 3, 3, 3, 3, 3,4, 4, 4, 4, 4, 4, 4, 4, 4),
                type = c('a', 'a', 'a', 'b', 'b', 'b','c','c','c','a', 'a', 'a', 
                         'b', 'b', 'b','c','c','c','a', 'a', 'a', 'b', 'b', 'b',
                         'c','c','c','a', 'a', 'a', 'b', 'b', 'b','c','c','c'), 
                randef = c('aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc',
                           'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 
                           'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 
                           'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'), 
                surv = sample(x = 1:200, size = 36, replace = TRUE), 
                nonsurv= sample(x = 1:200, size = 36, replace = TRUE))


# convert to survival and non survival into individuals following 
https://stackoverflow.com/questions/51519690/convert-cbind-format-for- binomial-glm-in-r-to-a-dataframe-with-individual-rows

x_long <- x %>%
  gather(code, count, surv, nonsurv)

# function to repeat a data.frame
x_df <- function(x, n){
  do.call('rbind', replicate(n, x, simplify = FALSE))
        }

# loop through each row and then rbind together
x_full <- do.call('rbind', 
                  lapply(1:nrow(x_long), 
                         FUN = function(i) x_df(x_long[i,], x_long[i, ]$count)))

# create binary_code
x_full$binary <- as.numeric(x_full$code == 'surv')

### binomial glm with interaction between time and type:
summary(fm2<-glm(binary ~ time*type, data = x_full, family = "binomial"))

### plot glm in ggplot2
ggplot(x_full, 
       aes(x = time, y = as.numeric(x_full$binary), fill= x_full$type)) +
   geom_smooth(method="glm", aes(color = factor(x_full$type)), 
               method.args = list(family = "binomial"))

### add randef to glmer
summary(fm3 <- glmer(binary ~ time * type + (1|randef), data = x_full, family = "binomial"))

### incorporate glmer in ggplot?
ggplot(x_full, aes(x = time, y = as.numeric(x_full$binary), fill= x_full$type)) +
  geom_smooth(method = "glmer", aes(color = factor(x_full$type)), 
              method.args = list(family = "binomial"))

В качестве альтернативы, как я могу подойти к этому, используя функцию прогнозирования и включить соответствие / ошибку в ggplot?

Любая помощь с благодарностью!

UPDATE

Даниэль предоставил здесь невероятно полезное решение, используя sjPlot и ggeffects здесь . Я приложил более длинное решение, используя прогнозирование, которое я собирался обновить в эти выходные. Надеюсь, это пригодится кому-то еще в том же положении!

newdata <- with(fm3, 
                expand.grid(type=levels(x$type),
                            time = seq(min(x$time), max(x$time), len = 100)))

Xmat <- model.matrix(~ time * type, newdata)
fixest <- fixef(fm3)
fit <- as.vector(fixest %*% t(Xmat))
SE <- sqrt(diag(Xmat %*% vcov(fm3) %*% t(Xmat)))
q <- qt(0.975, df = df.residual(fm3))

linkinv <- binomial()$linkinv
newdata <- cbind(newdata, fit = linkinv(fit), 
                 lower = linkinv(fit - q * SE),
                 upper = linkinv(fit + q * SE))

ggplot(newdata, aes(y=fit, x=time , col=type)) +
  geom_line() +       
  geom_ribbon(aes(ymin=lower, ymax=upper, fill=type), color=NA, alpha=0.4)

Ответы [ 2 ]

0 голосов
/ 25 ноября 2018

Большое спасибо Даниилу за предоставленное выше отличное решение. Надеемся, что это поможет следующему человеку, ищущему предложения, приведенный ниже код также работает для включения случайных эффектов и доверительных интервалов:

newdata <- with(fm3, expand.grid(type=levels(x_full$type),
                                    time = seq(min(x_full$time), max(x_full$time), len=100)))


Xmat <- model.matrix(~time * type, newdata)
fixest <- fixef(fm3)
fit <- as.vector(fixest %*% t(Xmat))
SE <- sqrt(diag(Xmat %*% vcov(fm3) %*% t(Xmat)))
q <- qt(0.975, df=df.residual(fm3))

linkinv <- binomial()$linkinv
newdata <- cbind(newdata, fit=linkinv(fit), 
             lower=linkinv(fit-q*SE),
             upper=linkinv(fit+q*SE))

ggplot(newdata, aes(y=fit, x=time , col=type)) +
  geom_line() +
  geom_ribbon(aes(ymin=lower, ymax=upper, fill=type), color=NA, alpha=0.4) 

и поскольку я забыл установить .seed в исходном сообщении, вот пример без случайных эффектов:

без RE

и со случайными эффектами, используя приведенный выше код:

и с RE

0 голосов
/ 23 ноября 2018

Я не уверен, что ваше обновление дает правильный график, потому что "линия регрессии" - это почти прямая линия, в то время как соответствующие КИ не симметричны линии.

Тем не менее, я думаю, что вы можете создать нужный вам сюжет с помощью sjPlot или ggeffects .

plot_model(fm3, type = "pred", terms = c("time", "type"), pred.type = "re")

pr <- ggpredict(fm3, c("time", "type"), type = "re")
plot(pr)

enter image description here

Если вы не хотите связывать свои прогнозы со случайными эффектами, просто пропустите pred.type соотв. type аргумент:

plot_model(fm3, type = "pred", terms = c("time", "type"))

pr <- ggpredict(fm3, c("time", "type"))
plot(pr)

enter image description here

Вы также можете построить свои прогнозы, обусловленные различными уровнями случайных эффектов, просто добавив термин случайного эффекта в terms -аргумент:

pr <- ggpredict(fm3, c("time", "type", "randef"))
plot(pr)

enter image description here

... или наоборот:

# NOTE! predictions are almost identical for each random
# effect group, so lines are overlapping!
pr <- ggpredict(fm3, c("time", "randef", "type"))
plot(pr)

enter image description here

Вы можете найти более подробную информацию в этой упаковке-виньетка .

...