计算向量中的连续数字 [英] Count consecutive numbers in a vector

查看:29
本文介绍了计算向量中的连续数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样的向量

If I have a vector like

"a": 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0

我想知道a中有多少个1,在这种情况下答案是3和2.

I want to know how many 1 are together in a, in this case the answer would be 3 and 2.

有没有可以做到这一点的脚本?

Is there any script that can do this?

推荐答案

参见 ?rle.

## create example vector
a <- c(rep(0, 3), rep(1, 3), rep(0, 4), rep(1, 2), rep(0, 3))

## count continuous values
r <- rle(a)

## fetch continuous length for value 1
r$lengths[r$values == 1]
# [1] 3 2

这篇关于计算向量中的连续数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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