Olivia
Olivia

Reputation: 814

R list into a single data frame cell

I'd like to change a list into one cell of a data frame.

  list <- list(1,2,3,4,5)

View(list)

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

I'd like to transform this such that it looks like:

          x
1 1,2,3,4,5

The reason is because I have a loop that is storing result in a list for each iteration, but I only want one cell per iteration.

There are other columns where for each iteration, there is only one result. So saving that in a data frame is easy. But then for the metric with multiple results, I don't want multiple columns or rows.

So I will have two data frames that I can use cbind on such that my final data frame will look like:

          x y
1 1,2,3,4,5 a
2     5,4,3 b

Upvotes: 2

Views: 8888

Answers (1)

Sotos
Sotos

Reputation: 51592

You can easily achieve that by unlist and paste, i.e.,

data.frame(x = paste(l1, collapse = ','))
#          x
#1 1,2,3,4,5

or simply (thanks @David)

data.frame(x = toString(list))
#              x
#1 1, 2, 3, 4, 5

On a side note, avoid naming your lists 'list' as there is a function called list in R

Upvotes: 7

Related Questions