Home > Net >  how to split list in R
how to split list in R

Time:08-21

I have a list in R as such:

DT <- data.table("columnA" = c(1,2,3), 
                 "columnB" = c(7,8,9), 
                 "columnC" = c(44,55,66))

list <- apply(DT, 2, as.list)

Now I would like to split the list, such that it only contains one single value for every columns:

result <- list(list(columnA = 1, 
                    columnB = 7, 
                    columnC = 44), 
               list(columnA = 2, 
                    columnB = 8, 
                    columnC = 55), 
               list(columnA = 3, 
                    columnB = 9, 
                    columnC = 66))

I came across the function split, but it requires a factor to split by. Is there an alternative function that does this without the factor?

This is a simplified example, but in my real data I have many more observations, many of which have the same values. The idea is that I create a list item for every row of the data.table

CodePudding user response:

You need a transposition.

purrr::transpose(list)

CodePudding user response:

  • We can use split form Base R
ul <- unlist(list , recursive = F)
split(ul , sub(".*(\\d)$" ,"\\1",  names(ul)))
  • Related