Question: Unlisting lists inside data frame and collapsing their values in R
0
gravatar for arronar
15 days ago by
arronar80
Austria
arronar80 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 • 108 views
ADD COMMENTlink modified 15 days ago by Chris Miller18k • written 15 days ago by arronar80
2
gravatar for Chris Miller
15 days ago by
Chris Miller18k
Washington University in St. Louis, MO
Chris Miller18k 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 15 days ago • written 15 days ago by Chris Miller18k
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: 1398 users visited in the last hour