【发布时间】:2020-09-29 02:04:10
【问题描述】:
我想使用 ggplot 生成许多线性回归图(细菌 OTU 与温度的关系图)。我希望这些图的标题是线性回归方程,我用一个函数来确定。该代码在我单独制作图时有效,但在我使用 for 循环时无效。
我不断收到以下错误:
Error in model.frame.default(formula = taxa_list[i] ~ Temperature, data = dataframe, :
variable lengths differ (found for 'Temperature')
请参阅下面的代码。我需要一个嵌套的 for 循环来完成这项工作吗?
taxa_list <- c("Vibrio","Salmonella","Campylobacter","Listeria","Streptococcus","Legionella")
taxa_list <- sort(taxa_list)
for (i in seq_along(taxa_list)) {
lm_eqn <- function(dataframe) {
m <- lm(taxa_list[i] ~ Temperature, dataframe)
p <- summary(m)
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2 %.% italic(x)*","~~italic(p)~"="~p0,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3),
p0 = format(p$coefficients[8], digits = 3)))
as.expression(eq);
}
plot <- ggplot(data = all_data, aes(x = Temperature, y = taxa_list[i], fill = taxa_list[i])) +
geom_point(data = all_data, aes(x = Temperature, y = taxa_list[i]), color = "black", size = 3) +
geom_smooth(method = "lm", size = 1, color = "black", fill = "gray") +
labs(title = lm_eqn(dataframe = all_data), subtitle = "") + xlab("Temperature") + ylab("Number of OTUs")
print(plot)
}
【问题讨论】:
-
将公式
taxa_list[i] ~ Temperature替换为as.formula(paste0(taxa_list[i], " ~ Temperature"))。
标签: r function for-loop ggplot2 nested-loops