Search code examples
rlisthierarchy

Rearrange hierarchy in a list of lists in R


I wonder if there exists a simple way to do the following thing in R:

Suppose I have a bunch of data on four cars: white BMW, black BMW, white GMC and black GMC.
I put them in a list of lists named cars:

data on white BMW is in cars[[1]][[1]],
data on black BMW is in cars[[1]][[2]],
data on white GMC is in cars[[2]][[1]],
data on black GMC is in cars[[2]][[2]].

In this case the first coordinate indicates make of the car, while the second indicates its colour.

I now wish to swap the coordinates so that the first coordinate would indicate colour, while the second would indicate the make of the car:

data on white BMW is in cars[[1]][[1]],
data on black BMW is in cars[[2]][[1]],
data on white GMC is in cars[[1]][[2]],
data on black GMC is in cars[[2]][[2]].

Thus I want to change the hierarchy in a list of lists.

Any help appreciated!


Solution

  • I don't think this is a super common task with lists. It sounds like it would be much better if you stored your data in a flat manner and just subset it as necessary. Nevertheless, here's one way you could swap. With the sample input

    cars <- list(list("white BMW", "black BMW"), list("white GMC", "black GMC"))
    

    you can do

    i <- 1:length(cars)
    j <- 1:length(cars[[1]])
    swap<-lapply(j, function(j) lapply(i, function(i) cars[[i]][[j]]))
    

    compare

    cars[[2]][[1]]
    # [1] "white GMC"
    swap[[2]][[1]]
    # [1] "black BMW"