broomパッケージを使ってみる

broomパッケージの上手な使い方を考えてる。

library(stargazer)
library(broom)
library(dplyr)
library(ggplot2)

res1 <- lm(yield ~ block + N + P + K, npk)
res2 <- lm(yield ~ block + N + P * K, npk)

# res <- res1
res <- res2

anova(res)
res %>% 
  aov() %>% 
  tidy()
summary(res)
tidy(res)

# 多重比較
res %>% 
  aov() %>% 
  TukeyHSD() %>% 
  tidy() %>%
  mutate(pair = paste(term, comparison, sep="_")) %>%
  ggplot(aes(colour=cut(adj.p.value, c(0, 0.01, 0.05, 1),
                        label=c("p<0.01","p<0.05","Non-Sig")))) +
  geom_hline(yintercept=0, lty="11", colour="grey30") +
  geom_errorbar(aes(pair, ymin=conf.low, ymax=conf.high), width=0.2) +
  geom_point(aes(pair, estimate)) +
  labs(colour="significance", title = "Tukey Honest Significant Differences") +
  coord_flip()

glance(res)
augment(res)

res %>% 
  tidy(conf.int = TRUE) %>% 
  filter(term != "(Intercept)") %>% 
  ggplot(aes(estimate, term, color = term)) +
  geom_point() +
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high)) +
  geom_vline(xintercept = 0)

stargazer(res1, res2, type="text", column.labels = c("res1","res2"),)