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!
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With