累积计数

扫码查看
本文介绍了累积计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法计算对象在R中累积出现在列中的次数?

Is there a way of counting the number of times an object appears in a column cumulatively in R?

例如。说我有栏:

id
1
2
3
2
2
1
2
3

这将变为:

id   count
1     1
2     1
3     1
2     2
2     3
1     2
2     4
3     2

等...

感谢

推荐答案

p> ave 函数按组计算函数。

The ave function computes a function by group.

> id <- c(1,2,3,2,2,1,2,3)
> data.frame(id,count=ave(id==id, id, FUN=cumsum))
  id count
1  1     1
2  2     1
3  3     1
4  2     2
5  2     3
6  1     2
7  2     4
8  3     2

我使用 id == id 创建一个 TRUE 值,当传递到 cumsum 时,它将转换为数字。您可以用 rep(1,length(id))替换 id == id

I use id==id to create a vector of all TRUE values, which get converted to numeric when passed to cumsum. You could replace id==id with rep(1,length(id)).

这篇关于累积计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:08
查看更多