问题:我有三个数据框,“d1”、“d2”和“d3”有三行,X1、X2 和值。我想用 X2 作为索引来绘制几条线。我想创建一个对每个数据帧执行相同操作的循环。该代码应适用于任何数据框。
我的代码
for (i in 1:3){
p<-as.name(paste("d", i, sep = ""))%>%
ggplot(aes(x=X1, y=value, colour=as.factor(X2)))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none")+
theme_classic2()
assign(paste("p", i, sep =""), p)
}
该函数在循环之外工作,但是当我运行循环时出现错误:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a character vector
我尝试时返回了相同的错误:
for (i in 1:3){
p<- ggplot(as.name(paste("d", i, sep = "")), aes(x=X1, y=value, colour=as.factor(X2)))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none")+
theme_classic2()
assign(paste("p", i, sep =""), p)
}
我在 SO 中找不到任何答案。
我认为这可能与paste()
循环内部有关。
希望有人可以提供帮助。