计算抛硬币序列中的交替次数
我有一个由 1 和 0 组成的序列,我想计算交替的次数,例如:
x <- rbinom(10, 1, 1/2)
> x
[1] 0 0 1 1 1 1 1 0 1 0
因此我想计算(在 R 中)序列从 1 到 0 交替(或翻转)的次数。在上面的序列中,交替次数(用手数)为 4。
I have a sequence of ones and zeros and I would like to count the number of alternations, e.g:
x <- rbinom(10, 1, 1/2)
> x
[1] 0 0 1 1 1 1 1 0 1 0
Thus I would like to count (in R) how many times the sequence alternates (or flips) from one to zero. In the above sequence, the number of alternations (counted by hand) is 4.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 diff() :
You can use diff() :
rle 函数将计算向量中相同值的“游程”次数。因此,该向量的长度(负 1)为您提供了更改的数量:
可能比 diff() 方法更快或更慢,但如果您需要它们,它也会为您提供游程长度...
The rle function will count the number of 'runs' of the same value in a vector. Hence the length of this vector (minus 1) gives you the number of alterations:
Might be quicker or slower than the diff() method, but it also gives you the run lengths if you need them...
它绝对不会在优雅方面击败 diff,但另一种方式:
在我的系统上,这似乎要快一点:
似乎应该有一个很好的分析解决方案来分配中不相等的相邻元素的数量顺序。
It definitely doesn't beat diff in terms of elegance but another way:
On my system, this seems to be a teeny bit faster:
It seems like there ought to be a nice analytic solution for the distribution of the number of unequal adjacent elements in the sequence.
伪代码(序列是一个包含硬币翻转的数组):
计数应该是你的结果
Pseudocode (sequence is an array with your coin flips):
count should be your result