R:计算单个列中连续出现的值

编程入门 行业动态 更新时间:2024-10-11 15:23:34
本文介绍了R:计算单个列中连续出现的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题与这个问题非常相似:值的出现的累积顺序

my question is very similar to this one: Cumulative sequence of occurrences of values

但是,如果当前行中的值与上一行不同,我想要重新启动计数。请查看以下输入和预期输出的示例。

But I would like the count of occurrences to 'restart' once the value in the current row is different from the previous row. Please find an example of input and expected output below.

dataset<-data.frame(input = c("a","b","b","a","a","c","a","a","a","a","b","c")) dataset$expected.output <- c(1,1,2,1,2,1,1,2,3,4,1,1) dataset

推荐答案

您需要使用 sequence 和 rle :

> sequence(rle(as.character(dataset$input))$lengths) [1] 1 1 2 1 2 1 1 2 3 4 1 1

更多推荐

R:计算单个列中连续出现的值

本文发布于:2023-10-31 09:08:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!