[英]R: How to count the number of consecutive occurrences in a longitudinal database with a length condition?
[英]How to count number of occurrences of a consecutive string of the same number in R
我在R中有這樣的字符串0和1:
x<-c(1,1,1,0,0,1,1,0,0,1,0,1,1,1,1,1,0,1,1,1)
我想算一下有多少個1的字符串(即中間沒有0)。 對於這里的示例,我想獲得輸出4,因為有4個連續的1字符串。
讓我知道我是否應該澄清我的意思。
在此先感謝您的幫助!
我們可以嘗試rle
sum(with(rle(x), lengths[!!values])>1)
$[1] 4
要么
sum(with(rle(x!=0), lengths*values)>1)
還是用rleid
library(data.table)
sum(table(rleid(x)[x!=0])>1)
#[1] 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.