Reputation: 566
What is the quickest way to get from the following list:
set.seed(1)
mylist <- list(1:2,1:3,1:4)
names(mylist) <- sample(LETTERS,3)
mylist
$J
[1] 1 2
$V
[1] 1 2 3
$Z
[1] 1 2 3 4
to a list with an extra vector containing the names of list i.e.
mylist
$J
[1] 1 2
[2] J J
$V
[1] 1 2 3
[2] V V V
$Z
[1] 1 2 3 4
[2] Z Z Z Z
the result could equally be a list of data frames. Some sort of
lapply(mylist, function(x) { data.frame(x=x,y=names(x)})
Upvotes: 1
Views: 161
Reputation: 55420
Personally, I like @Matthew Plourde's use of stack
Here's an option using mapply
that preserves the same structure of the original list
mapply(function(L, N)
{names(L) <- rep(N, length(L)); L}, mylist, names(mylist))
$G
G G
1 2
$J
J J J
1 2 3
$N
N N N N
1 2 3 4
Upvotes: 4
Reputation: 44614
Another option:
df<-stack(mylist)
split(df, df$ind)
Maybe stack(mylist)
is all you really need?
Upvotes: 10