如何在R矩阵中查找具有相同名称的列的每行标准差?
要查找R矩阵中具有相同名称的列的每行标准差,我们可以按照以下步骤操作:
首先,创建一个包含一些具有相同名称的列的矩阵。
然后,使用`tapply`结合`colnames`和`sd`函数来查找具有相同名称的列的每行标准差。
示例
创建矩阵
让我们创建一个如下所示的矩阵:
M<-matrix(rpois(100,5),ncol=4) colnames(M)<-c("C1","C2","C1","C2") M
输出
执行上述脚本后,将生成以下输出(由于随机化,此输出将在您的系统上有所不同):
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
广告