I have two lists in R of identical length and would like to combine them into a data frame with the total number of rows in the resulting data frame equivalent to the length of the two lists (in other words, each list is a column). When I tried using c(list1, list2)
the two lists were appended together and when I used cbind(list1, list2)
the total number of observations was almost double the original length.
Asked
Active
Viewed 8,408 times
2

josliber
- 43,891
- 12
- 98
- 133

g.humpkins
- 331
- 6
- 15
1 Answers
5
Try
do.call(rbind.data.frame, Map('c', list1, list2))
data
list1 <- as.list(1:5)
list2 <- as.list(6:10)

akrun
- 874,273
- 37
- 540
- 662
-
I used the last piece of code and received an error saying "Error in data.frame(Col1 = unlist(lat_long_zip_key), Col2 = unlist(listing_id)) : arguments imply differing number of rows: 57246, 57258" However, when I run the length of the two lists, `length(listing_id) [1] 57258` and `length(lat_long_zip_key) [1] 57258` they appear to have the same length. Any suggestions? – g.humpkins Jun 11 '15 at 04:28
-
@g.humpkins I was assuming that your list elements have the same length, but if that is not the case, the `unlist` in both list will return different length. Can you show a small reproducible example that shows the error? – akrun Jun 11 '15 at 04:29
-
Ah, I was able to get it to work with your first code snippet, thanks! Do you have any clue why when I test the length of the lists, they are equivalent, but when I used the `unlist` code they were not? – g.humpkins Jun 11 '15 at 04:37
-
1@g.humpkins You are looking at the `length` of the entire list and from your description, both lists have the same length. But, what if some elements inside that list different in length or nrow etc? Try to check `sapply(listing_id, length)` or `lengths(listiing_id)` (in R 3.2.0) – akrun Jun 11 '15 at 04:39