How to count how many times a value occurs after another

I am new to R, but I need to use it to find out how many times one value happens after another. Basically, I have 5 numbers (0,1,2,3,4) that are randomly listed 38 times. I need to find out how many times the value 0 occurs after 0, 1 happens after 0, 2 after 0 ... so on, until I reach 4, it happens after 4. Is there any command for this?

Really appreciate the help!

+6
r
source share
2 answers

Create a data frame from 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 gives an initial frame of pairs data along with a column of Freq counts:

 as.data.frame(table(pairs)) 
+11
source share

perhaps this command does this:

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

All Articles