通过满足给定条件的行将数据帧分为多个块 [英] Spliting dataframe into chunks by the rows that satisfy the given condition

查看:32
本文介绍了通过满足给定条件的行将数据帧分为多个块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下数据框:

I have a dataframe similar to:

 col1   col2
 1      10
 1      30
 2      60
 3      20
 3      12
 3      51
 3      11

当col2中的值大于50时,我想将此数据帧分为多个小块:

I want to divide this dataframe into chanks when the value in col2 is bigger than 50:

dataframe #1    
col1   col2
1      10
1      30
2      60

dataframe #2
col1   col2
3      20
3      12
3      51

dataframe #3
col1   col2
3      11

我已经尝试过 split 函数,但是它不能用于此任务。我想知道是否有通用功能来实现这一目标?

I have tried split function but it would not serve for this task. I wonder if there is a generic function to achieve this?

推荐答案

您可以使用 cumsum 分割中的c $ c>,其中很多 rev 包含了上一行col2> 50的行组

You can use cumsum in split, with a lot of reving to include the rows where col2 > 50 in the previous group

rev(split(df, rev(cumsum(rev(df$col2 > 50)))))
#@joran method, (same result, except for names): 
split(df, cumsum(df$col2 > 50) - (df$col2 > 50))

输出:

# $`2`
#    col1 col2
# 1:    1   10
# 2:    1   30
# 3:    2   60
# 
# $`1`
#    col1 col2
# 1:    3   20
# 2:    3   12
# 3:    3   51
# 
# $`0`
#    col1 col2
# 1:    3   11

没有全部 rev s你会得到这个

without all the revs you get this

split(df, cumsum(df$col2 > 50))

# $`0`
#    col1 col2
# 1:    1   10
# 2:    1   30
# 
# $`1`
#    col1 col2
# 1:    2   60
# 2:    3   20
# 3:    3   12
# 
# $`2`
#    col1 col2
# 1:    3   51
# 2:    3   11

这篇关于通过满足给定条件的行将数据帧分为多个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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