Unlisting lists inside data frame and collapsing their values in R
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
• 13,961 views
•
link
2 answers
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=":")
}
}
• 0 views
•
link
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=":")))
• 0 views
•
link
Log in to answer this question.