我有一个名为“proc.r1”的 21 个不同数据框的列表。
我正在尝试制作 21 个图表,每个图表都使用来自列表中每个数据框的数据。
我在下面所做的仅适用于列表中的第一个数据框。我为“plotdf1”编写的 ggplot 是我需要从每个数据框生成的图形。所以我需要 21 个外观相同的“plotdf1”,但每个都将显示来自不同数据框的数据。
#making the first data frame in the "proc.r1" list as a separate data frame
df1 <- as.data.frame(proc.r1 [[1]])
#making all the NA values displayed as 0
df1[is.na(df1)] <- 0
#rounding off the "norm.n" column, which I'll use as a label in the plot, to just 1 decimal point
df1 [,42] <- round(df1[,42],1)
plotdf1 <- ggplot(df1)+geom_rect(aes(xmin=0,xmax=5,ymin=0,ymax=5))+facet_grid(row~col)+geom_text(aes(x=2.5,y=2.5,label=norm.n,colour="white"))
有没有办法循环这个,以便我可以生成 21 个图形?
我真的不想在“df21”之前制作“df1”,“df2”,df3”等,然后将所有名称复制到这几行函数中,并且必须执行“plotdf1”,“plotdf2”,“plotdf3” ”等。
如果这个问题令人困惑,请告诉我。
提前致谢!
最佳答案
比较简单:
for(i in 1:length(proc.r1)
{
df1 = as.data.frame(proc.r1[[i]])
df1[is.na(df1)] <- 0
df1[,42] <- round(df1[,42],1)
plotdf1 <- ggplot(df1)+geom_rect(aes(xmin=0,xmax=5,ymin=0,ymax=5))+
facet_grid(row~col)+geom_text(aes(x=2.5,y=2.5,label=norm.n,colour="white"))
print(plotdf1)
}
使用
lapply
也可以,因为你有一个列表,但我更喜欢 for
在这里循环,因为你没有返回任何东西。
关于r - 从数据框列表制作多个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21564736/