You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中高效获取特定值的连续出现序列长度?

筛选特定值的连续出现长度(基于rle()函数)

rle()函数会返回一个包含values和lengths的列表。目前我还没找到无需两次调用rle()、也不用先将输出保存到对象再进行子集化(额外步骤)的方法,来筛选出特定值的连续出现序列长度。

例如,在模拟公平硬币抛掷的正面(用1表示)连续出现情况时:

s <- sample(c(0,1),100,T)
rle(s)
# Run Length Encoding
#   lengths: int [1:55] 1 2 1 2 1 2 1 2 2 1 ...
#   values : num [1:55] 0 1 0 1 0 1 0 1 0 1 ...

# 两次调用方式:
rle(s)[[1]][rle(s)[[2]]==1]
#  [1] 2 2 2 2 1 1 1 1 6 1 1 1 2 2 1 1 2 2 2 2 2 3 1 1 4 1 2

# 中间步骤方式:
r <- rle(s)
r$lengths[r$values==1]
#  [1] 2 2 2 2 1 1 1 1 6 1 1 1 2 2 1 1 2 2 2 2 2 3 1 1 4 1 2

我发现只需修改rle()的代码即可轻松获取仅针对1的连续出现长度,但或许存在更简便的方法。


内容的提问来源于stack exchange,提问作者Antoni Parellada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:45:38