Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count how many times a value occurs after another

Tags:

r

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!

like image 617
clattenburg cake Avatar asked Feb 14 '11 17:02

clattenburg cake


2 Answers

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
like image 54
kohske Avatar answered Oct 03 '22 23:10

kohske


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))
like image 30
G. Grothendieck Avatar answered Oct 04 '22 00:10

G. Grothendieck