r - 如何使用循环或应用使用不同的变量重复此代码?
问题描述
我想简化下面的代码,这样我就不会为所有三个变量写出相同的代码。
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))
我研究了循环和应用系列,并认为其中一个应该可以工作,但不知道如何工作。
解决方案
推荐阅读
- video - 从服务器(使用 Apache 或 Ngnix)流式传输视频并将其发送到 EXO 播放器的过程?
- r - 在 1 个变量和变量列表之间执行所有可能的线性回归
- python - 如何让一个类在 Python 中继承其父级的值?
- django - Django DRF 字段存在但序列化程序无法识别它
- c++ - 当我们将类类型的参数传递给 cpp 中的函数时会发生什么?
- python - 有没有办法让这段代码更短更简单,即通过使用某种 for 循环?
- node.js - 节点语法参考
- python - 无法使用 sys 和线程库输入和运行 python 代码
- python - 有没有办法只允许一种类型的输入,例如只有浮点数、整数来自 input() 调用?
- django - NOT NULL 约束失败:accounts_sellerprofile.user_id