R 计算向量中出现的某些数字对

R 计算向量中出现的某些数字对,r,count,R,Count,如何计算数据帧的向量或列中的某些数字对,有什么好的解决方案吗 我有这样的数据,我想计算一下向量中有多少对组合为23(或其他组合)。或者2在3之前出现多少次 set.seed(1) sample(1:5, 50, replace=T) 结果应该是: number combination count 2 3 2 4 1 4 5 4 3 我尝试了函数匹配,但在两个数字的组合中它不起作用 任

如何计算数据帧的向量或列中的某些数字对,有什么好的解决方案吗

我有这样的数据,我想计算一下向量中有多少对组合为23(或其他组合)。或者2在3之前出现多少次

 set.seed(1)
 sample(1:5, 50, replace=T)
结果应该是:

number combination   count
2 3                  2
4 1                  4
5 4                  3
我尝试了函数匹配,但在两个数字的组合中它不起作用

任何帮助都将不胜感激,

马丁

你可以试试这样的东西:

x <- sample(1:50, 50, rep=T)
table(paste(x[-length(x)], x[-1]))
# with dplyr
y <- data.frame(x=paste(x[-length(x)], x[-1]))
summarise(group_by(y,x), N=n())
# or if you need to keep the first and second value
x <- sample(1:5, 50, rep=T)
y <- data.frame(x1=x[-length(x)], x2=x[-1])
summarise(group_by(y, x1, x2), N=n())

x您可以尝试以下方法:

x <- sample(1:50, 50, rep=T)
table(paste(x[-length(x)], x[-1]))
# with dplyr
y <- data.frame(x=paste(x[-length(x)], x[-1]))
summarise(group_by(y,x), N=n())
# or if you need to keep the first and second value
x <- sample(1:5, 50, rep=T)
y <- data.frame(x1=x[-length(x)], x2=x[-1])
summarise(group_by(y, x1, x2), N=n())
x使用表格:

set.seed(1)
sample(1:5, 50, replace=T)
## [1] 2 2 3 5 2 5 5 4 4 1 2 1 4 2 4 3 4 5 2 4 5 2 4 1 2 2 1 2 5 2 3 3 3 1 5 4 4 1 4 3 5 4 4 3 3 4 1 3 4 4
table(data.frame(first=x[-length(x)],second=x[-1]))
##      second
## first 1 2 3 4 5
##     1 2 0 2 4 1
##     2 1 3 2 1 1
##     3 4 1 5 2 3
##     4 2 4 2 1 2
##     5 0 0 4 2 0
因此,5对为0,31对为4,33对为5。

使用表格:

set.seed(1)
sample(1:5, 50, replace=T)
## [1] 2 2 3 5 2 5 5 4 4 1 2 1 4 2 4 3 4 5 2 4 5 2 4 1 2 2 1 2 5 2 3 3 3 1 5 4 4 1 4 3 5 4 4 3 3 4 1 3 4 4
table(data.frame(first=x[-length(x)],second=x[-1]))
##      second
## first 1 2 3 4 5
##     1 2 0 2 4 1
##     2 1 3 2 1 1
##     3 4 1 5 2 3
##     4 2 4 2 1 2
##     5 0 0 4 2 0

所以5对是0,31对是4,33对是5。

这也是个不错的选择。这也是个不错的选择。不错:)这正是我想要的。不错:)这正是我想要的。