-1

I have a list in R that looks something like this.

> list.data <- list(c(1,2,3), c(4,5), c(6,7,8,9,10))
> list.data
[[1]]
[1] 1 2 3

[[2]]
[1] 4 5

[[3]]
[1]  6  7  8  9 10

(The actual list is much longer and has close to a 1000 elements with each element of different length)

I want to combine the elements of the above list into a single data frame, so that the output look something like this. The ID represents the list element from which the corresponding value has been derived

Essentially it should look like the following data frame created directly using R Code.

> list.data.final <- data.frame("ID"=numeric(10), "value"=numeric(10))
> list.data.final$ID <- c(1,1,1,2,2,3,3,3,3,3)
> list.data.final$value <- 1:10
> list.data.final
   ID value
1   1     1
2   1     2
3   1     3
4   2     4
5   2     5
6   3     6
7   3     7
8   3     8
9   3     9
10  3    10

The ID is the list element from which the value is derived. The Value column has all the values from the list.

Is there a way to do this?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Arpit
  • 53
  • 5
  • I realised that the output data frame is not showing correctly in the question. Essentially it should look like the following data frame created directly using R Code. – Arpit Jan 15 '18 at 19:43

1 Answers1

2

Try this:

list.data <- list(c(1,2,3), c(4,5), c(6,7,8,9,10))
data.frame(
  id=rep(seq_along(list.data), lengths(list.data)),
  value=unlist(list.data)
)
#    id value
# 1   1     1
# 2   1     2
# 3   1     3
# 4   2     4
# 5   2     5
# 6   3     6
# 7   3     7
# 8   3     8
# 9   3     9
# 10  3    10

In hindsight, the question is a duplicate of From list to data frame (again...) keeping element names as row names ... and I'm glad to see that I came up with a similar answer! The only distinctions being that that q/a relied on a named-list, this one has no names; and it used sapply(..., length), where lengths (released around R-3.2) may be more efficient.

r2evans
  • 141,215
  • 6
  • 77
  • 149