Transpose a List of Lists

后端 未结 5 2024
我寻月下人不归
我寻月下人不归 2020-12-01 23:32

I have a list which contains list entries, and I need to transpose the structure. The original structure is rectangular, but the names in the sub-lists do not match.

5条回答
  •  旧时难觅i
    2020-12-02 00:01

    While this is an old question, i found it while searching for the same problem, and the second hit on google had a much more elegant solution in my opinion:

    list_of_lists <- list(a=list(x="ax", y="ay"), b=list(w="bw", z="bz"))
    new <- do.call(rbind, list_of_lists) 
    

    new is now a rectangular structure, a strange object: A list with a dimension attribute. It works with as many elements as you wish, as long as every sublist has the same length. To change it into a more common R-Object, one could for example create a matrix like this:

    new.dims <- dim(new)
    matrix(new,nrow = new.dims[1])
    

    new.dims needed to be saved, as the matrix() function deletes the attribute of the list. Another way:

    new <- do.call(c, new) 
    dim(new) <- new.dims
    

    You can now for example convert it into a data.frame with as.data.frame() and split it into columns or do column wise operations. Before you do that, you could also change the dim attribute of the matrix, if it fits your needs better.

提交回复
热议问题