I have a list of 21 different data frames called "proc.r1".
I'm trying to make 21 graphs, each one using data from each of the data frame in the list.
What I did below only works with the first data frame in the list. The ggplot I wrote for "plotdf1" is the graph I need generated from each data frame. So I need 21 of identical-looking "plotdf1" except that each one would display data from different data frames.
#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"))
Is there a way I can loop this so that I can generate 21 graphs? I don't really want to make "df1", "df2", df3", etc etc until "df21" then copy all the names into those few lines of functions and have to do "plotdf1", "plotdf2", "plotdf3", etc etc.
Please let me know if this question is confusing.
Thanks in advance!
Creating a list of Dataframes. To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.
Create Plot Spanning Multiple Rows or Columns To create a plot that spans multiple rows or columns, specify the span argument when you call nexttile . For example, create a 2-by-2 layout. Plot into the first two tiles. Then create a plot that spans one row and two columns.
Combining a list of data frames into a single data frame. (Similarly using cbind or dplyr::bind_cols for columns.) To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce with merge (or some other joining function) to get them together.
List with DataFrame columns as items. You can also use tolist() function on individual columns of a dataframe to get a list with column values. In the above example, we iterate through each column of the dataframe which is converted to a list and then appended to ls .
It's relatively simple:
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)
}
Using lapply
is also possible since you have a list, but I prefer a for
loop here since you're not returning anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With