Unlisting lists inside data frame and collapsing their values in R
2
1
Entering edit mode
6.6 years ago
arronar ▴ 280

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

R lists unlist dataframe • 12k views
ADD COMMENT
2
Entering edit mode
6.6 years ago

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 COMMENT
1
Entering edit mode
3.4 years ago
opplatek ▴ 280

If you don't want to use for loop you can just use a combination of apply (to iterate over columns) and sapply (to iterate over lists).

# Apply to all columns
apply(myDataFrame, 2, function(y) sapply(y, function(x) paste(unlist(x), collapse=":")))

# Apply to all columns but the first one
apply(myDataFrame[, -1], 2, function(y) sapply(y, function(x) paste(unlist(x), collapse=":")))
ADD COMMENT

Login before adding your answer.

Traffic: 2020 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6