问题
I have list like this,
myList <- lapply(unique(diamonds$cut), function(x){
lst <- lapply(unique(diamonds$color), function(y){
dta <- diamonds[diamonds$cut == x & diamonds$color == y, ]
lm(price ~ carat, data = dta)
})
names(lst) <- unique(diamonds$color)
return(lst)
})
names(myList) <- unique(diamonds$cut)
The structure is,
> str(myList, max.level=2)
List of 5
$ Ideal :List of 7
..$ E:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ I:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ J:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ H:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ F:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ G:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ D:List of 12
.. ..- attr(*, "class")= chr "lm"
$ Premium :List of 7
..$ E:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ I:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ J:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ H:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ F:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ G:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ D:List of 12
.. ..- attr(*, "class")= chr "lm"
$ Good :List of 7
..$ E:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ I:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ J:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ H:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ F:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ G:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ D:List of 12
.. ..- attr(*, "class")= chr "lm"
$ Very Good:List of 7
..$ E:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ I:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ J:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ H:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ F:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ G:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ D:List of 12
.. ..- attr(*, "class")= chr "lm"
$ Fair :List of 7
..$ E:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ I:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ J:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ H:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ F:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ G:List of 12
.. ..- attr(*, "class")= chr "lm"
..$ D:List of 12
.. ..- attr(*, "class")= chr "lm"
I want to restructure this after having myList
so that Each color
will comes before cut
. I can not change the code that creates myList
. I have to do it after myList
is generated. Some Help plz.
回答1:
It might not be ideal, but as long as the list structure is regular, you could use a nested for loop:
# get names of inner and outer lists
innerNames <- names(myList[[1]])
outerNames <- names(myList)
# creat new blank list
myList2 <- list()
# restructure
for(i in innerNames) {
for(j in outerNames)
if(j == outerNames[1]) myList2[[i]] <- myList[[j]][i]
else myList2[[i]] <- c(myList2[[i]], myList[[j]][i])
}
}
来源:https://stackoverflow.com/questions/36646594/change-the-hierarchy-of-a-list-in-r