0

I would like to simplify the code below so that I do not write out the same code for all three variables.

set.seed(16)
commercial.mean <- rnorm(n = 50, mean = 0, sd = 1)
multi_fam.mean <- rnorm(n = 50, mean = 0, sd = 1)
single_fam.mean <- rnorm(n = 50, mean = 0, sd = 1)
UV_inf <- rbinom(n=50, size=1, prob=0.4)
t1 <- data.frame(cbind(commercial.mean, multi_fam.mean, single_fam.mean, UV_inf))


summary_df <- t1 %>% group_by(UV_inf) %>%
  do(tidy(lm_robust(commercial.mean ~ 1, data = .))) %>%
  mutate(commercial.mean = estimate)
a1 <- ggplot(summary_df, aes(UV_inf, commercial.mean)) +
  geom_point(size = 3)  + xlab("") +ylab("") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0) +
  geom_point(data = t1, position = position_jitter(width = 0.1), alpha = 0.3) +
  theme_bw()+ggtitle("Commercial")+theme(plot.title = element_text(size = 12))


summary_df <- t1 %>% group_by(UV_inf) %>%
  do(tidy(lm_robust(multi_fam.mean ~ 1, data = .))) %>%
  mutate(multi_fam.mean = estimate)
a2 <- ggplot(summary_df, aes(UV_inf, multi_fam.mean)) +
  geom_point(size = 3)  + xlab("") +ylab("") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0) +
  geom_point(data = t1, position = position_jitter(width = 0.1), alpha = 0.3) +
  theme_bw()+ggtitle("Multi-family")+theme(plot.title = element_text(size = 12))

summary_df <- t1 %>% group_by(UV_inf) %>%
  do(tidy(lm_robust(single_fam.mean ~ 1, data = .))) %>%
  mutate(single_fam.mean = estimate)
a3 <- ggplot(summary_df, aes(UV_inf, single_fam.mean)) +
  geom_point(size = 3)  + xlab("") +ylab("") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0) +
  geom_point(data = t1, position = position_jitter(width = 0.1), alpha = 0.3) +
  theme_bw()+ggtitle("Single-family")+theme(plot.title = element_text(size = 12))

I've looked into looping and the apply family and think that one of those should work but cannot figure out how.

kar12
  • 1
  • Where did the `lm_robust` function come from? – Tung May 13 '19 at 05:21
  • 1
    You can build a function then use `map` or `lapply` to pass each variable to it. See these https://stackoverflow.com/a/49648729/ & https://stackoverflow.com/a/50930640/ – Tung May 13 '19 at 05:28

0 Answers0