R累加和按条件复位 [英] R cumulative sum by condition with reset

查看:132
本文介绍了R累加和按条件复位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据框架中有一个数字向量,如下所示。

  df<  -  data.frame a = c(1,2,3,4,2,3,4,5,8,9,10,1,2,1))

我需要创建一个新的列,它提供比其前身更大的条目的运行计数。得到的列向量应该是:

  0,1,2,3,0,1,2,3,4, 5,6,0,1,0 

我的尝试是创建一个flag列的diff标记值何时更大。

  df $ flag < -  c(0,diff(df $ a)> 0)
> df $ flag
[1] 0 1 1 1 0 1 1 1 1 1 1 0 1 0

然后,我可以应用一些dplyr组/总和魔术几乎得到正确的答案,除了当flag == 0时不会重置总和:

  df%>%group_by(flag)%>%mutate(run = cumsum(flag))

a标志运行
1 1 0 0
2 2 1 1
3 3 1 2
4 4 1 3
5 2 0 0
6 3 1 4
7 4 1 5
8 5 1 6
9 8 1 7
10 9 1 8
11 10 1 9
12 1 0 0
13 2 1 10
14 1 0 0

我不想诉诸一个for()循环,因为我有几个这些运行总和在数据框架中计算几十万行。

解决方案

这里有一种方法, [1] 0 1 2 3 0 1 2 3 4 5 6 0 1 0

我们可以通过 diff(df) $ a)< 0 。向量中的位置小于其前辈。我们将 c(F,..)添加到第一个位置。该向量的累积和创建一个分组索引。函数 ave 可以对该索引执行一个函数,我们使用 seq_along 来运行计数。但是,从1开始,我们减去一个 ave(...) - 1 从零开始。



< hr>

使用 dplyr 的类似方法:

 $($)
df%>%
group_by(cumsum(c(FALSE,diff(a)< 0)))%>%
mutate (row_number() - 1)


I have a vector of numbers in a data.frame such as below.

df <- data.frame(a = c(1,2,3,4,2,3,4,5,8,9,10,1,2,1))

I need to create a new column which gives a running count of entries that are greater than their predecessor. The resulting column vector should be this:

0,1,2,3,0,1,2,3,4,5,6,0,1,0

My attempt is to create a "flag" column of diffs to mark when the values are greater.

df$flag <- c(0,diff(df$a)>0)
> df$flag
 [1] 0 1 1 1 0 1 1 1 1 1 1 0 1 0

Then I can apply some dplyr group/sum magic to almost get the right answer, except that the sum doesn't reset when flag == 0:

df %>% group_by(flag) %>% mutate(run=cumsum(flag))

    a flag run
1   1    0   0
2   2    1   1
3   3    1   2
4   4    1   3
5   2    0   0
6   3    1   4
7   4    1   5
8   5    1   6
9   8    1   7
10  9    1   8
11 10    1   9
12  1    0   0
13  2    1  10
14  1    0   0

I don't want to have to resort to a for() loop because I have several of these running sums to compute with several hundred thousand rows in a data.frame.

解决方案

Here's one way with ave:

ave(df$a, cumsum(c(F, diff(df$a) < 0)), FUN=seq_along) - 1
 [1] 0 1 2 3 0 1 2 3 4 5 6 0 1 0

We can get a running count grouped by diff(df$a) < 0. Which are the positions in the vector that are less than their predecessors. We add c(F, ..) to account for the first position. The cumulative sum of that vector creates an index for grouping. The function ave can carry out a function on that index, we use seq_along for a running count. But since it starts at 1, we subtract by one ave(...) - 1 to start from zero.


A similar approach using dplyr:

library(dplyr)
df %>% 
  group_by(cumsum(c(FALSE, diff(a) < 0))) %>% 
  mutate(row_number() - 1)

这篇关于R累加和按条件复位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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