简体   繁体   English

R:如何计算1的数量并写入向量

[英]R: How to count number of 1 and write to vector

I have as signal-vector that looks like this: 我有信号矢量,看起来像这样:

a <- c(1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1) a < - c(1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,1,0,0 ,0,0,0,0,0,0,0,0,0,1,1,1)

I will count how often a 1 occurs in one raw and write that in to a vector b eg for vector a it should result in: 我将计算1在一个raw中出现的频率,并将其写入向量b,例如对于向量a,它应该导致:

b b
5,2,1,1,1,1,3 5,2,1,1,1,1,3

The reason is that i will plot a histogram that shows me the distribution of the length of the events. 原因是我将绘制一个直方图,显示事件长度的分布。 Maybe there is already a function in R that does exactly that? 也许在R中已经有一个功能正是如此? Otherwise with if-loop? 否则使用if-loop?

Cheers Greg 干杯格雷格

You could try rle (Note that these solutions are also from base R ) 您可以尝试rle (请注意,这些解决方案也来自base R

with(rle(a), lengths[!!values])
#[1] 5 2 1 1 1 1 3

Or 要么

unname(table(cumsum(c(1,abs(diff(a)))))[c(TRUE, FALSE)])
#[1] 5 2 1 1 1 1 3

If the vector is not binary 如果向量不是二进制的

with(rle(a), lengths[values==1])
#[1] 5 2 1 1 1 1 3

Or 要么

unname(table(cumsum(c(1,abs(diff(a==1)))))[c(TRUE, FALSE)])

EDIT 编辑

If the vector starts with numbers other than 1 . 如果向量以1以外的数字开头。 For example 0 or 2 (as mentioned by @Ananda Mahto in the comments) 例如02 (如评论中的@Ananda Mahto所述)

 a[1] <- 2
 a1 <- a[which(a==1)[1]:length(a)]
 unname(table(cumsum(c(1,abs(diff(a1==1)))))[c(TRUE, FALSE)])
 #[1] 4 2 1 1 1 1 3
 with(rle(a), lengths[values==1])
 #[1] 4 2 1 1 1 1 3

Or 要么

with(rle(a == 1), lengths[values]) # from @Richard Scriven's comments

Shameless plug, but since you are only dealing with ones and zeroes, you could also use TrueSeq from my "SOfun" package ( only on GitHub ). 无耻的插头,但因为你是只处理1和0,你也可以使用TrueSeq从(我的“SOfun”包仅在GitHub上 )。

Here's what TrueSeq does: 这是TrueSeq作用:

library(SOfun)
TrueSeq(as.logical(a))
#  [1] 1 1 1 1 1 0 0 0 0 2 2 0 0 0 3 0 4 0 5 0 6 0 0 0 0 0 0 0 0 0 0 0 7 7 7

Keeping that in mind, you can just use tabulate on the output since that would discard the zeroes: 牢记这一点,您可以在输出上使用tabulate ,因为这会丢弃零:

tabulate(TrueSeq(as.logical(a)))
# [1] 5 2 1 1 1 1 3

Another solution with base R : base R的另一个解决方案:

count1<-strsplit(paste(a,collapse=""),"0")[[1]]
b<-nchar(count1[count1!=""])

> b
[1] 5 2 1 1 1 1 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM