R使用表示和开/关切换的列拆分data.frame [英] R Split data.frame using a column that represents and on/off switch

查看:93
本文介绍了R使用表示和开/关切换的列拆分data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下所示:

a <- data.frame(cbind(x=seq(50),
                      y=rnorm(50),
                      z=c(rep(0,5),
                          rep(1,8),
                          rep(0,3),
                          rep(1,2),
                          rep(0,12),
                          rep(1,12),
                          rep(0,8))))

我想在列上分割data.frame a z ,但将每个组作为单独的 data.frame 作为列表的成员,即在我的示例中为前5个行将是列表中的第一个项目,接下来的8行将是列表中的下一个项目,接下来的3行将是该项目之后的其他项目等。

I would like to split the data.frame a on the column z but have each group as a separate data.frame as a member of a list i.e. in my example the first 5 rows would be the first item in the list the next 8 rows would be the next item in the list, the next 3 rows would be item after that etc. etc.

简单的因素将所有的1个组合在一起,并将所有的0组合在一起...

Simple factors combine all the 1s together and all the 0s together...

我确定有一个简单的方法来做到这一点,女人

I'm sure that there is a simple way to do this, but it has eluded for at the moment.

谢谢

推荐答案

尝试 rleid 函数 data.table v> 1.9.5

library(data.table)
split(a, rleid(a$z))
# $`1`
#   x           y z
# 1 1 -0.03737561 0
# 2 2 -0.48663043 0
# 3 3 -0.98518106 0
# 4 4  0.09014355 0
# 5 5 -0.07703517 0
# 
# $`2`
#     x          y z
# 6   6  0.3884339 1
# 7   7  1.5962833 1
# 8   8 -1.3750668 1
# 9   9  0.7987056 1
# 10 10  0.3483114 1
# 11 11 -0.1777759 1
# 12 12  1.1239553 1
# 13 13  0.4841117 1
....

这篇关于R使用表示和开/关切换的列拆分data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆