Question: Unlisting lists inside data frame and collapsing their values in R
0
gravatar for arronar
5 months ago by
arronar120
Austria
arronar120 wrote:

Hello I have this data.frame and as you can see there are lists inside some cells.

myList1 <- list()
myList1[[1]] <- 0
myList1[[2]] <- list(3)
myList1[[3]] <- list(6)
myList1[[4]] <- list(7, 9)

myList <- list()
myList[[1]] <- list(1, 4, 6, 7)
myList[[2]] <- list(2, 7, 3)
myList[[3]] <- list(5, 5, 3, 9, 6)
myList[[4]] <- list(7, 9)

myDataFrame <- data.frame(row = c(1,2,3,4))

myDataFrame$col1 <- myList1
myDataFrame$col2 <- myList

the data frame looks like:

row   col1          col2
   1    0           list(1, 4, 6, 7)
   2    list(3)     list(2, 7, 3)
   3    list(6)     list(5, 5, 3, 9, 6)
   4    list(7, 9)  list(7, 9)

Is there any way to unlist the lists and collapse with colon symbol, their items in order to make the dataframe look like the following ?

 row   col1           col2
   1    0             1:4:6:7
   2    3             2:7:3
   3    6             5:5:3:9:6
   4    7:9           7:9

Thank you

unlist dataframe lists R • 212 views
ADD COMMENTlink modified 5 months ago by Chris Miller19k • written 5 months ago by arronar120
2
gravatar for Chris Miller
5 months ago by
Chris Miller19k
Washington University in St. Louis, MO
Chris Miller19k wrote:

My first thought is that you should examine your choices that got you to this point and choose a better data representation.

If you must fix this problem as described, then something like this should work:

for(i in 1:length(myDataFrame[,1])){
    if(is.list(myDataFrame[i,3])){
        myDataFrame[i,3]=paste(unlist(myDataFrame[i,3]),collapse=":")
    }
}
ADD COMMENTlink modified 5 months ago • written 5 months ago by Chris Miller19k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 965 users visited in the last hour