开发者

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 t开发者_运维技巧his?

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜