Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: split elements of a list into sublists

Tags:

list

r

I have a data frame with following structure:

pat <- c(rep(1,50), rep(2,50), rep(3,50))
inc <- rep(c(rep(1,5), rep(2,5), rep(3,5), rep(4,5), rep(5,5),
             rep(6,5), rep(7,5), rep(8,5), rep(9,5), rep(10,5)), 3)
df <- data.frame(cbind(pat, inc))

df is split into a list of elements:

all.inc = split(df, inc)

Now I want to split each element of this list into sub-lists. Something like:

all.pat = split(all.inc, pat)

This doesn't work, obviously. I've already tried the plyr functions and lapply, but didn't get it to work.

Any ideas?

like image 479
Markus Avatar asked Sep 14 '12 08:09

Markus


2 Answers

Use lapply:

lapply(all.inc, function(x) split(x, x$pat))
like image 69
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 21 '22 14:10

A5C1D2H2I1M1N2O1R2T1


If you'd like to split your data frame all at once, you could use

split(df, interaction(df$pat,df$inc))

However, the returned value will be a single list of data frames, which is slightly different from what you would get by splitting list elements.

like image 8
BenBarnes Avatar answered Oct 21 '22 13:10

BenBarnes