计算 R 中某个值出现的次数 [英] Counting the number of occurrences of a value in R

查看:43
本文介绍了计算 R 中某个值出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 R 中有一个数字向量.

If I have a vector of numbers in R.

numbers <- c(1,1, 2,2,2, 3,3, 4,4,4,4, 1)

我想返回一个向量,该向量提供该值沿向量累积出现的次数.即

I want to return a vector that provides the number of times that value has occurred cumulatively along the vector. I.e.

results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)

推荐答案

我们可以使用 ave 并通过与 'numbers' vector 分组来应用 seq_along

We can use ave and apply the seq_along by grouping with the 'numbers' vector

ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3

这篇关于计算 R 中某个值出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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