如何在R矩阵中找到同名列的行中位数?
要在 R 矩阵中查找同名列的行中位数,我们可以按照以下步骤操作 -
首先,创建一个矩阵,其中一些列具有相同的名称。
然后,使用 tapply 以及 colnames 和中值函数来查找具有相同名称的列的行中值。
示例
创建矩阵
让我们创建一个矩阵,如下所示 -
M<-matrix(rpois(150,10),ncol=6)输出结果colnames(M)<-c("C1","C1","C2","C2","C1","C2")
M
执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-
C1 C1 C2 C2 C1 C2[1,] 7 2 7 13 4 10
[2,] 20 8 10 8 15 12
[3,] 8 11 6 19 9 11
[4,] 10 10 9 8 8 8
[5,] 7 17 10 9 9 10
[6,] 9 10 8 6 11 13
[7,] 8 7 10 11 7 13
[8,] 8 11 10 16 4 9
[9,] 12 8 13 7 8 9
[10,] 6 7 7 14 15 11
[11,] 9 6 17 12 12 13
[12,] 11 8 8 10 13 8
[13,] 9 9 9 8 6 10
[14,] 7 11 11 8 11 11
[15,] 13 13 9 10 10 12
[16,] 5 10 4 13 15 6
[17,] 8 10 6 8 12 3
[18,] 8 9 10 8 7 7
[19,] 14 14 14 8 3 11
[20,] 7 13 10 8 8 9
[21,] 7 10 8 5 15 9
[22,] 8 8 5 8 11 13
[23,] 9 13 4 9 6 19
[24,] 12 11 5 7 7 7
[25,] 14 12 8 10 12 4
查找具有相同名称的列的行中位数
使用 tapply 以及 colnames 和中值函数来查找矩阵 M 中具有相同名称的列的行中值 -
M<-matrix(rpois(150,10),ncol=6)输出结果colnames(M)<-c("C1","C1","C2","C2","C1","C2")
t(apply(M,1, function(x) tapply(x,colnames(M),median)))
C1 C2[1,] 4 10
[2,] 15 10
[3,] 9 11
[4,] 10 8
[5,] 9 10
[6,] 10 8
[7,] 7 11
[8,] 8 10
[9,] 8 9
[10,] 7 11
[11,] 9 13
[12,] 11 8
[13,] 9 9
[14,] 11 11
[15,] 13 10
[16,] 10 6
[17,] 10 6
[18,] 8 8
[19,] 14 11
[20,] 8 9
[21,] 10 8
[22,] 8 8
[23,] 9 9
[24,] 11 7
[25,] 12 8
以上是 如何在R矩阵中找到同名列的行中位数? 的全部内容, 来源链接: utcz.com/z/331655.html