【发布时间】:2021-05-09 06:13:53
【问题描述】:
我正在尝试在具有不同值的相同变量的多个数据帧上绘制相同的图表。我有 n 个名为 df_1、df_2 ... df_n 的数据帧,我的代码如下所示:
#Create dataframes(In this example n = 3)
df_1 <- data.frame(a1 = 1:1000,
b1 = 1:1000)
df_2 <- data.frame(a1 = 1:1000,
b1 = 1:1000)
df_3 <- data.frame(a1 = 1:1000,
b1 = 1:1000)
##Store dataframes in list
example.list<-lapply(1:3, function(x) eval(parse(text=paste0("df_", x)))) #In order to store all datasets in one list using their name
names(example.list)<-lapply(1:3, function(x) paste0("df_", x))
#Graph and save for each dataframe
for (i in example.list){
benp <- ggplot(i, aes(x=b1)) +
geom_histogram(fill="steelblue", aes(y=..density.., alpha=..count..), bins=60) +
labs(title="Beneficios", subtitle="") + ylab("Densidad") +
xlab("Beneficios ($millones)") +
geom_vline(aes(xintercept=mean(b1)), color="red4",linetype="dashed") +
theme(legend.position = "none") +
annotate("text", x= mean(b1), y=0, label=round(mean(b1), digits = 2),
colour="red4", size=3.5, vjust=-1.5, hjust=-0.5)
ggsave(benp, file=paste0(i,"_histogram.png"))
}
我收到错误消息“平均值错误(b1):找不到对象 b1”。我不知道如何告诉 R b1 来自数据帧 i。有谁知道我的代码有什么问题,或者是否有一些更简单的方法可以绘制多个数据帧?提前致谢!
【问题讨论】:
-
嗨,Andres,您能创建一个可重现的示例来分享吗?
-
嗨,雷克斯。我改变了我的帖子,所以它可以成为一个可重复的例子
-
别担心,@Andres。请在下面查看我的回答,如果它适合您,请接受它。