计算r中的连续年数 [英] Counting the number of consecutive years in r

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

问题描述

我有一个包含年份的向量A:例如.

I have a vector A containing years: eg.

A <- c(1978, 1979, 1980, 1981, 1984, 1987,1988,1989,1990,1991, 1992)

我希望能够计算出错过一年之前的年份.因此,我希望我的答案是:4、1、6

I would like to be able to count the sequence of years before a year is missed out. So I would be looking for my answer to be : 4, 1, 6

我知道将 rle 用于重复的数字序列,但是不确定在这里做什么.

I know about using rle for sequences of repeated numbers but not sure what to do here.

推荐答案

假设 A 已排序:

A <- c(1978, 1979, 1980, 1981, 1984, 1987,1988,1989,1990,1991, 1992)
B <- cumsum(c(1, diff(A)>1))
rle(B)$lengths
#[1] 4 1 6

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

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