glacierbliss
glacierbliss

Reputation: 102

R putting list inside data frame

I'm stuck trying to figure out how to get a list or vector into a data frame. Here's a minimal example.

#list or matrix "a"
a=rbind(c(1,2,3),c(4,5,6),c(7,8,9))
#data frame "b"
b=data.frame(veg=c("potato","pumpkin","carrot"))

Now I want to put row 1 of a into a new column and observation 1 of b e.g. b$counts. Then row 2 of a goes into observation 2 of b$counts. Does that make sense? I have searched all that I could think of to get this, but am at a loss for how to do it.

Upvotes: 0

Views: 32

Answers (1)

akrun
akrun

Reputation: 887971

We can have a list column by splitting by row

b$counts <- asplit(a, 1)
b
#        b  counts
#1  potato 1, 2, 3
#2 pumpkin 4, 5, 6
#3  carrot 7, 8, 9

Or use split by seq_len(nrow(a))

b$count <- split(a, seq_len(nrow(a)))

Upvotes: 1

Related Questions