Augusto D'Arruda
Augusto D'Arruda

Reputation: 53

How can I find the numbers of runs in a list?

I have a list called 'toss' with 100 coins tosses. toss[[1]] gives me this (just example)

0 1 0 0 1 1 1 0 0 0 1 1 0 1

And i want to find out the number of runs i have.

In this case, it should give me 8, because:

0 | 1 | 0 0 | 1 1 1 | 0 0 0 | 1 1 | 0 | 1 --> 8 runs

Since I have 100 tosses, i need to compute the run count (R) for every toss.

How can I do that?

I tried using the rle() function but it didn't work.

Upvotes: 2

Views: 806

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47330

2 other ways:

sum(vec[-1]!=vec[-length(vec)])+1
# [1] 8

sum(abs(diff(vec)))+1
# [1] 8

Both are basically counting the changes and adding 1.

They're a bit faster:

toss <- sample(0:1,1000000,replace = T)
library(microbenchmark)
microbenchmark(
  rle_  = lengths(rle(toss))[[1]],
  diff_ = sum(abs(diff(toss)))+1,
  uneq  = sum(toss[-1]!=toss[-length(toss)])+1,
  unit = "relative"
)
# Unit: relative
#  expr      min       lq      mean   median       uq       max neval
#  rle_ 3.050793 4.797267 2.2994769 1.827826 2.170513 1.0883327   100
# diff_ 1.485904 1.456412 0.8871846 1.132103 1.119984 0.2089307   100
#  uneq 1.000000 1.000000 1.0000000 1.000000 1.000000 1.0000000   100

Upvotes: 2

akrun
akrun

Reputation: 887531

The output of rle is a named list of lengths and values.

str(rle(toss))
#List of 2
# $ lengths: int [1:8] 1 1 2 3 3 2 1 1
# $ values : num [1:8] 0 1 0 1 0 1 0 1
# - attr(*, "class")= chr "rle"

Extract either the lengths or values and get the length

length(rle(toss)$lengths)

The functions lengths will get length of each list element and then extract the first length

lengths(rle(toss))[[1]]

data

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

Upvotes: 3

Related Questions