R - headers based on nested lists

I have 2 lists, and inside each there are two more lists containing data frames (in other words, nested lists). I want to build each data frame and call it a base on the names of both primary and nested lists.

For example, let's say that we have:

a=list(
  list(a=data.frame(x=rpois(5,1),y=rpois(5,1)),
       b=data.frame(x=rpois(5,1),y=rpois(5,1))),
  list(c=data.frame(x=rpois(5,1),y=rpois(5,1)),
       d=data.frame(x=rpois(5,1),y=rpois(5,1))))

And we have the names of the main list:

names(a)=c("alpha","bravo")

Inside the two primary lists alphaand bravowe have two more lists: charlieand delta:

for(i in 1:length(a)) {
  names(a[[i]])=c("charlie","delta") }

lapply , (alpha bravo) (charlie delta) . , : alpha_charlie, alpha_delta, bravo_charlie bravo_delta.

lapply(a,function(i) {
  lapply(names(i), function(j) { 
    ggplot()+
      geom_point(data=i[[j]],aes(x,y))+
      opts(title=paste(names(i),j,sep="_")) #Here is where I am struggling!
    } ) } )

. !

+3
3

lapply .

lapply(seq(a), function(i){
    lapply(seq(a[[i]]), function(j){
        ggplot() +
        geom_point(data = a[[i]][[j]], aes(x, y))+
        opts(title = paste(names(a)[i], names(a[[i]])[j], sep = "_"))
        })})
+4

, for . , grid.arrange do.call.

library(ggplot2)

plot_list = list() # Save plots to list.

for (name_1 in names(a)) {
    for (name_2 in names(a[[name_1]])) {
        title_string = paste(name_1, name_2, sep="_")

        plt = ggplot(data=a[[name_1]][[name_2]], aes(x=x, y=y)) +
              geom_point() +
              opts(title=title_string)

        plot_list[[title_string]] = plt
    }
}

library(gridExtra)
png("plots.png", height=600, width=600)
do.call(grid.arrange,  plot_list)
dev.off()

enter image description here

+3

The first time you lost names, so it ends up being yucky. Dason gave you a good decision.

However, I think you would be much better off if you converted the list of data.frames into a single data.frame! and use the cut!

nested.fun <- function(l) {
  out <- ldply(l, data.frame)
  names(out)[1] <- 'inner.id'
  return(out)
}

one.df <- ldply(a, nested.fun)

ggplot(one.df, aes(x,y))+geom_point()+facet_grid(.id~inner.id)
+2
source

All Articles