AleXXXMarks
AleXXXMarks

Reputation: 1

Calculate mean of colnames and rownames set in matrix in R

Apologies if this has been asked elsewhere but I couldn't find an answer.

I'm attempting to calculate the mean of a matrix I've created, using colMeans and rowMeans. The mean values are what I want to populate the matrix with, and have set the rows and columns using vectors

Currently my code looks like this:

A = matrix(ncol = (14), # number of columns in matrix
       nrow = (10), # number of rows in matrix
       colMeans(A, na.rm = FALSE, dims = colnames(A)),
       rowMeans(A, na.rm = FALSE, dims = rownames(A)),
       byrow = TRUE)
colnames(A) c("2","4","6","8","10","12","14","16","18","20","22","24","26","28")
rownames(A) <- c("10","20","30","40","50","60","70","80","90","100")

A

Running this returns a matrix with NA values.

Expected output would be a matrix like below, where NA values are replaced by the mean of the column and row numbers.

For example the first intersection would equal 6, as 2+10/2

    2  4  6  8 10 12 14 16 18 20 22 24 26 28
10  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
20  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
30  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
40  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
50  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
60  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
70  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
80  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
90  NA NA NA NA NA NA NA NA NA NA NA NA NA NA
100 NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Upvotes: 0

Views: 200

Answers (1)

Stephen Henderson
Stephen Henderson

Reputation: 6532

This is essentially what you want using the outer function. Note that t transposes the matrix so it's the right way round that you specify above.It could also just be outer(B,A, fn)

A<-seq(2,28,2)
B<-seq(10,100,10)
fn<-function(A,B)(A+B)/2
t(outer(A,B, fn))


      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
 [1,]    6    7    8    9   10   11   12   13   14    15    16    17    18    19
 [2,]   11   12   13   14   15   16   17   18   19    20    21    22    23    24
 [3,]   16   17   18   19   20   21   22   23   24    25    26    27    28    29
 [4,]   21   22   23   24   25   26   27   28   29    30    31    32    33    34
 [5,]   26   27   28   29   30   31   32   33   34    35    36    37    38    39
 [6,]   31   32   33   34   35   36   37   38   39    40    41    42    43    44
 [7,]   36   37   38   39   40   41   42   43   44    45    46    47    48    49
 [8,]   41   42   43   44   45   46   47   48   49    50    51    52    53    54
 [9,]   46   47   48   49   50   51   52   53   54    55    56    57    58    59
[10,]   51   52   53   54   55   56   57   58   59    60    61    62    63    64

Upvotes: 1

Related Questions