list R:将列表的元素拆分为子列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12420994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
R: split elements of a list into sublists
提问by Markus
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:
df 被拆分为一个元素列表:
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.
这显然行不通。我已经尝试了plyr
功能和lapply
,但没有让它工作。
Any ideas?
有任何想法吗?
采纳答案by A5C1D2H2I1M1N2O1R2T1
Use lapply
:
使用lapply
:
lapply(all.inc, function(x) split(x, x$pat))
回答by BenBarnes
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.
但是,返回值将是单个数据框列表,这与拆分列表元素所得到的值略有不同。