按值拆分data.frame [英] Split data.frame by value

查看:101
本文介绍了按值拆分data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何拆分以下data.frame

how can I split the following data.frame

df <- data.frame(var1 = c("a", 1, 2, 3, "a", 1, 2, 3, 4, 5, 6, "a", 1, 2), var2 = 1:14)

列入

a 1
1 2
2 3
3 4

a 5
1 6
2 7
3 8
4 9
5 10
6 11

a 12
1 13
2 14

所以基本上,列1中的值a是我想要分割数据帧的标签/标识符。我知道分割函数,但这意味着我必须添加另一列,因为从我的示例可以看出,组的大小可能会有所不同,我不知道如何自动创建这样一个虚拟列以满足我的需要。

So basically, value "a" in column 1 is the tag / identifier I want to split the data frame on. I know about the split function but that means I have to add another column and since, as can be seen from my example, the size of the groups can vary I do not know how to automatically create such a dummy column to fit my needs.

有什么想法?

干杯,

Sven

推荐答案

您可以找到索引向量的哪个值等于a,然后根据该值创建一个分组变量然后使用split。

You could find which values of the indexing vector equal "a", then create a grouping variable based on that and then use split.

df[,1] == "a"
# [1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
#[13] FALSE FALSE
cumsum(df[,1] == "a")
# [1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3
split(df, cumsum(df[,1] == "a"))
#$`1`
#  var1 var2
#1    a    1
#2    1    2
#3    2    3
#4    3    4
#
#$`2`
#   var1 var2
#5     a    5
#6     1    6
#7     2    7
#8     3    8
#9     4    9
#10    5   10
#11    6   11
#
#$`3`
#   var1 var2
#12    a   12
#13    1   13
#14    2   14

这篇关于按值拆分data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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