首页 > 解决方案 > 如何使用循环或应用使用不同的变量重复此代码?

问题描述

我想简化下面的代码,这样我就不会为所有三个变量写出相同的代码。

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))

我研究了循环和应用系列,并认为其中一个应该可以工作,但不知道如何工作。

标签: r

解决方案


推荐阅读