Maylo
Maylo

Reputation: 562

Expand rows with lists as observations

I have the following frame:

df <- structure(list(returns = list(c(1,2,3,4,5,6), c(7,8,9,10,11,12)), indexId = c("a", "b")), class = "data.frame", row.names = 1:2)

Is there an easy way to convert this into a normal data.frame so it appears as:

Choice ppl
   1   a
   2   a
   3   a
   4   a
   5   a
   6   a
   7   b
   8   b
   9   b
  10   b
  11   b
  12   b

I have a solution using For but I am looking for something simpler.

All help is much appreciated!

Upvotes: 1

Views: 25

Answers (2)

r.user.05apr
r.user.05apr

Reputation: 5456

Or :

data.frame(choice = unlist(df$returns), ppl = rep(df$indexId, lapply(df$returns, length)))

Upvotes: 3

AntoniosK
AntoniosK

Reputation: 16121

df <- structure(list(returns = list(c(1,2,3,4,5,6), c(7,8,9,10,11,12)), 
                     indexId = c("a", "b")), class = "data.frame", row.names = 1:2)

library(tidyverse)

df %>% separate_rows()

#    returns indexId
# 1        1       a
# 2        2       a
# 3        3       a
# 4        4       a
# 5        5       a
# 6        6       a
# 7        7       b
# 8        8       b
# 9        9       b
# 10      10       b
# 11      11       b
# 12      12       b

Upvotes: 3

Related Questions