0

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.

Maximilian
  • 4,177
  • 7
  • 46
  • 85
  • So how many items are there in a full list? I'm a little confused by the in your list data. Can you give some more detail about how the list is formed? Also, will it always be the Town field missing? – ThatGuy May 31 '14 at 08:35
  • Please post the output from `dput( list )` so we can reconstruct your data easily. – Simon O'Hanlon May 31 '14 at 09:21
  • @Eddie: the can be easily placed by other name once in dataframe as `colname(datafame) <- c("Column1","Column2","Column3")`. Why the binding doesn't work is because each `[[i]]` list isn't same length. – Maximilian May 31 '14 at 12:00

1 Answers1

2

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))
talat
  • 68,970
  • 21
  • 126
  • 157