clattenburg cake
clattenburg cake

Reputation: 1222

How to count how many times a value occurs after another

I'm new to R but I need to use it to find out how many times one value occurs after another. Basically, I have 5 numbers (0,1,2,3,4) listed in a random order 38 times. I need to find out how many times the value 0 occurs after 0, 1 occurs after 0, 2 after 0... so on, until I reach 4 occurs after 4. Is there any command to do this?

Really appreciate the help!

Upvotes: 6

Views: 2295

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269694

Create a data frame of pairs and then use table :

z <- c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4)
pairs <- data.frame(first = head(z, -1), second = tail(z, -1))
table(pairs)

giving:

     second
first 0 1 2 3 4
    0 0 2 0 0 0
    1 0 0 2 0 0
    2 0 0 0 2 0
    3 0 0 0 0 2
    4 1 0 0 0 0

or this which gives the original pairs data frame along with a Freq column of counts:

as.data.frame(table(pairs))

Upvotes: 10

kohske
kohske

Reputation: 66852

probably this command do that:

library(plyr) # if absent, type > install.packages('plyr')
z <- sample(0:4, 38, T) # data
count(data.frame(embed(rev(z),2))) # do it

Upvotes: 10

Related Questions