Maximilian
Maximilian

Reputation: 4229

Bind list with unequal columns

After countless SO contributions about binding list of data, I'm embarrased to ask this question. However, I cannot seems to find on SO and come up with the right solution myself.

I have list which looks like this:

[[1]]
          223586            <NA> 
       "James J." "Adress xxxxx" 

[[2]]
         12693738           <NA>         <NA> 
     "Oliver M." "Address yyyyy" "Town xxxxx"

What I would like to get is: The missing filled with NA

                          <NA>       <NA>
         James J. Adress xxxxx       NA
         Oliver M. Address yyyyy town xxxx   

I'm getting the last column (lenght 2) filled with name (first column entry) James J. in this case:

  do.call(rbind.data.frame, list)

             NA         NA        NA  
         James J. Adress xxxxx   James J.
         Oliver M. Address yyyyy town xxxx 

EDIT: There is nothing particular about this data. It is more about how to bind unequal length of data in list. There are either lapply(list, function(x) length(x)) length of 2 or 3 strings.

So I would like to replace the missing length 2 with NA so that the list can be bind.

Upvotes: 0

Views: 1367

Answers (1)

talat
talat

Reputation: 70286

The answer to your question can be found in this related question on the right. If you want to change your list elements so that they are all of the same length, you can do:

lst <- list(a = 1:3, b = 1:4, name = c("A", "X"))  #a list for the example

n <- max(unlist(lapply(lst, length)))              #check maximum length

lstnew <- lapply(lst, function(x) {ans <- rep(NA, length=n); 
                                   ans[1:length(x)]<- x; 
                                   return(ans)})   #Add NA for elements shorter than n

And then convert your list to whatever you need. Or, much shorter, you could use sapply:

sapply(lst,'[',1:n)         #to return a matrix

or if you need a data.frame

as.data.frame(sapply(lst,'[',1:n))

or

as.data.frame(lapply(lst,'[',1:n))

Upvotes: 2

Related Questions