【发布时间】:2017-08-01 03:56:22
【问题描述】:
我一直在尝试创建一个 for 循环,该循环将遍历我的数据框并为我拥有的每个单独的 ID 制作相同的图。以下是一些示例数据:
TJID1 <- c("TJ22", "TJ22", "TJ23", "TJ23", "TJ23", "TJ24", "TJ24")
Day <- c("2005-11-22", "2005-11-23", "2006-12-01", "2006-12-02", "2006-12-03","2005-07-08", "2005-07-08")
Mean.Depth <- c (2, 2, 3, 4, 5, 6, 6)
SE.Depth <- c(1, 1, 2, 2, 1, 2, 2)
sample <- cbind(TJID1, Day, Mean.Depth, SE.Depth)
sample <- as.data.frame(sample)
我将每个人设置为不同的 TJ 编号,然后对于每个 TJ,他们有不同的每日深度平均值。每个人的日子都不同。我已经能够通过每个单独的 TJ TJ22 <- sample [sample$TJID1 == "TJ22", ] 对主数据框进行子集化。然后我的情节代码是(使用子集数据框):
DailyMeans_TJ22 <- ggplot(TJ22, aes(x=Day, y=Mean.Depth))+
geom_point()+
geom_line()+
geom_errorbar(aes(ymin=Mean.Depth-1.96*SE.Depth, ymax=Mean.Depth+1.96*SE.Depth), width = 0.5, col="red")
我想创建一个 for 循环,它只循环遍历每个人并制作相同的情节。这是我目前所拥有的:
var_list = combn(names(sample) [3:4], 3, simplify=FALSE)
plot_list = list()
for (i in unique (sample$TJID1)){
TJ <- sample[sample$TJID1== i,]
p = ggplot(TJ, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
geom_point()+
geom_line()
plot_list[[i]] = p
}
但这实际上并没有给我任何东西。任何帮助表示赞赏!
【问题讨论】:
-
你必须
print(p)。为什么不直接使用facet_wrap(~TJID1)而不是循环呢?
标签: r loops for-loop plot ggplot2