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?
我是R的新手,但是我需要用它来找出一个值接一个出现多少次。基本上,我有5个数字(0,1,2,3,4)以随机顺序列出38次。我需要找出值0在0之后发生了多少次,1发生在0之后,2之后发生在0 ......所以,直到我达到4发生在4.之后是否有任何命令要执行此操作?
Really appreciate the help!
真的很感激帮助!
2 个解决方案
#1
11
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:
或者这给出了原始对数据框以及Freq列的计数:
as.data.frame(table(pairs))
#2
10
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
#1
11
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:
或者这给出了原始对数据框以及Freq列的计数:
as.data.frame(table(pairs))
#2
10
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