R - title plots based on nested lists

list, nested-lists, r

Solution

You could use lapply on an indexing sequence instead of the names themselves.

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 = "_"))
        })})

Problem

I have 2 lists, and inside each are two more lists containing data frames (in other words, nested lists). I want plot each data frame and title it based on the names of both the primary and nested lists. For example, say 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 primary list: ``` names(a)=c("alpha","bravo") ``` Inside the two primary lists `alpha` and `bravo`, we have two more lists, `charlie` and `delta`: ``` for(i in 1:length(a)) { names(a[[i]])=c("charlie","delta") } ``` I can use `lapply` to loop through each list and plot the data frames, but I am having trouble getting the titles to combine the name of the primary list (`alpha` and `bravo`) and the nested list (`charlie` and `delta`) for each data frame. For instance, in this case, I would like to have four plots called: `alpha_charlie`, `alpha_delta`,`bravo_charlie`, and `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! } ) } ) ``` Any help would be much appreciated. Thank you!

Original source