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