本文介绍了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:计算单个列中连续出现的值
发布评论