如何在 R 中查找矩阵的行模式?
R 里没有内置函数用于查找模式,因此我们需要创建一个,然后将其应用于矩阵的行。对于模式,函数的创建如下 −
mode<-function(x){which.max(tabulate(x))}
现在考虑我们有一个矩阵 M,我们就可以应用上述函数,如下所示 −
apply(M2,1,mode)
示例 1
> M1<-matrix(sample(1:2,25,replace=TRUE),ncol=5) > M1
输出
[,1] [,2] [,3] [,4] [,5] [1,] 2 2 1 2 2 [2,] 2 2 2 2 1 [3,] 2 2 1 1 1 [4,] 2 1 1 1 1 [5,] 2 1 1 2 2
> apply(M1,1,mode)
输出
[1] 2 2 1 1 2
示例 2
> M2<-matrix(sample(1:2,100,replace=TRUE),ncol=5) > M2
输出
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 2 2 1 [2,] 2 1 1 2 1 [3,] 2 2 1 1 1 [4,] 2 1 1 2 2 [5,] 2 1 1 2 2 [6,] 1 2 1 1 2 [7,] 1 1 2 1 2 [8,] 2 2 1 2 1 [9,] 2 1 1 2 2 [10,] 1 1 2 2 2 [11,] 1 1 2 1 2 [12,] 1 2 2 2 1 [13,] 2 2 2 2 1 [14,] 2 1 2 2 1 [15,] 1 2 1 1 2 [16,] 2 2 1 2 1 [17,] 2 2 1 1 1 [18,] 2 1 1 2 1 [19,] 1 1 1 2 1 [20,] 2 1 1 2 2
> apply(M2,1,mode)
输出
[1] 1 1 1 2 2 1 1 2 2 2 1 2 2 2 1 2 1 1 1 2
示例 3
> M3<-matrix(sample(1:3,100,replace=TRUE),ncol=5) > M3
输出
[,1] [,2] [,3] [,4] [,5] [1,] 1 3 3 2 1 [2,] 2 3 1 2 2 [3,] 2 2 3 3 1 [4,] 1 3 1 3 2 [5,] 3 1 2 1 2 [6,] 2 3 1 1 1 [7,] 2 2 2 3 1 [8,] 1 2 2 2 2 [9,] 2 1 2 1 2 [10,] 1 3 1 2 1 [11,] 2 1 3 1 1 [12,] 1 1 3 2 2 [13,] 2 1 1 1 2 [14,] 2 1 3 3 2 [15,] 1 2 3 1 2 [16,] 1 2 1 2 1 [17,] 3 1 1 3 2 [18,] 3 3 3 3 1 [19,] 3 2 3 1 1 [20,] 3 3 2 2 1
> apply(M3,1,mode)
输出
[1] 1 2 2 1 1 1 2 2 2 1 1 1 1 2 1 1 1 3 1 2
示例 4
> M4<-matrix(sample(9:10,100,replace=TRUE),ncol=5) > M4
输出
[,1] [,2] [,3] [,4] [,5] [1,] 10 10 9 10 9 [2,] 9 9 10 9 9 [3,] 9 9 9 10 10 [4,] 10 9 9 10 10 [5,] 10 10 9 10 9 [6,] 10 10 9 10 10 [7,] 9 9 9 10 9 [8,] 9 10 9 10 9 [9,] 9 9 9 9 9 [10,] 9 10 9 10 9 [11,] 10 10 9 9 9 [12,] 9 9 9 9 9 [13,] 10 10 10 9 10 [14,] 10 9 10 10 10 [15,] 9 10 9 10 9 [16,] 9 10 9 10 9 [17,] 9 10 10 9 10 [18,] 9 9 9 9 10 [19,] 10 9 9 10 9 [20,] 10 9 9 10 9
> apply(M4,1,mode)
输出
[1] 10 9 9 10 10 10 9 9 9 9 9 9 10 10 9 9 10 9 9 9
广告