Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

r - Combining lists of different lengths into data frame

I have data like the SampleData below, which has lists of different length that I'd like to combine in to a data frame like the Desired Result below. I've tried using lapply and cbind.na from the qpcR package like the example below, but for some reason it won't let me turn the result into a data frame. If I just used two of the lists and cbind.na it will combine them and add the NA to the end like I want, but when I try using it in lapply it just leaves them as a list of different length lists. Any tips are greatly appreciated.

SampleData<-list(list(1,2,3),list(1,2),list(3,4,6,7))

Desired Result:
structure(list(V1 = c(1, 2, 3, NA), V2 = c(1, 2, NA, NA), V3 = c(3, 
4, 6, 7)), .Names = c("V1", "V2", "V3"), row.names = c(NA, -4L
), class = "data.frame")


Example Code:

lapply(SampleData,qpcR:::cbind.na)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a modified version with length<- assignment

setNames(do.call(cbind.data.frame, lapply(lapply(SampleData, unlist), 
        `length<-`, max(lengths(SampleData)))), paste0("V", 1:3))
#  V1 V2 V3
#1  1  1  3
#2  2  2  4
#3  3 NA  6
#4 NA NA  7

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...