使用apply函数从其他矩阵的列的方式创建新矩阵

时间:2021-07-14 22:57:46

I have data matrix like the below, I want to make another matrix from it, such that the columns of new matrix is the mean of some columns of original matrix.

我有如下所示的数据矩阵,我想从中制作另一个矩阵,这样新矩阵的列就是原始矩阵的某些列的平均值。

my matrix:

我的矩阵:

> A
      A1 A2 B1 B2 E3 E5 E6 E7 E8  E9
 [1,]  1 11 21 31 41 51 61 71 81  91
 [2,]  2 12 22 32 42 52 62 72 82  92
 [3,]  3 13 23 33 43 53 63 73 83  93
 [4,]  4 14 24 34 44 54 64 74 84  94
 [5,]  5 15 25 35 45 55 65 75 85  95
 [6,]  6 16 26 36 46 56 66 76 86  96
 [7,]  7 17 27 37 47 57 67 77 87  97
 [8,]  8 18 28 38 48 58 68 78 88  98
 [9,]  9 19 29 39 49 59 69 79 89  99
[10,] 10 20 30 40 50 60 70 80 90 100

My new Matrix B, should contain 3 columns, which first column is the mean of A1,A2, 2th columns is mean of B1,B2, 3th column is mean of E3,E5,...

我的新Matrix B应该包含3列,其中第一列是A1,A2的平均值,第2列是B1,B2的平均值,第3列是E3,E5的平均值,...

How can I implement this with apply function

如何使用apply函数实现此功能

B<-apply(A,2, mean)

2 个解决方案

#1


1  

Using apply you could do

使用应用你可以做到

a <- apply(d, 1, function(x) {
  by(as.vector(x), substr(names(x) , 1, 1), mean)
})
t(a)

The inner function splits the data by the first letters of the variable names and calculates mean values.

内部函数通过变量名的前几个字母分割数据并计算平均值。

       A  B  E
 [1,]  6 26 66
 [2,]  7 27 67
 [3,]  8 28 68
 [4,]  9 29 69
 [5,] 10 30 70
 [6,] 11 31 71
 [7,] 12 32 72
 [8,] 13 33 73
 [9,] 14 34 74
[10,] 15 35 75

#2


0  

Is this what you mean?

你是这个意思吗?

sapply(unique(substr(colnames(A),1,1)), function(x) apply(A[,grepl(x,colnames(A))],1,mean))
       A  B  E
 [1,]  6 26 66
 [2,]  7 27 67
 [3,]  8 28 68
 [4,]  9 29 69
 [5,] 10 30 70
 [6,] 11 31 71
 [7,] 12 32 72
 [8,] 13 33 73
 [9,] 14 34 74
[10,] 15 35 75

#1


1  

Using apply you could do

使用应用你可以做到

a <- apply(d, 1, function(x) {
  by(as.vector(x), substr(names(x) , 1, 1), mean)
})
t(a)

The inner function splits the data by the first letters of the variable names and calculates mean values.

内部函数通过变量名的前几个字母分割数据并计算平均值。

       A  B  E
 [1,]  6 26 66
 [2,]  7 27 67
 [3,]  8 28 68
 [4,]  9 29 69
 [5,] 10 30 70
 [6,] 11 31 71
 [7,] 12 32 72
 [8,] 13 33 73
 [9,] 14 34 74
[10,] 15 35 75

#2


0  

Is this what you mean?

你是这个意思吗?

sapply(unique(substr(colnames(A),1,1)), function(x) apply(A[,grepl(x,colnames(A))],1,mean))
       A  B  E
 [1,]  6 26 66
 [2,]  7 27 67
 [3,]  8 28 68
 [4,]  9 29 69
 [5,] 10 30 70
 [6,] 11 31 71
 [7,] 12 32 72
 [8,] 13 33 73
 [9,] 14 34 74
[10,] 15 35 75