R: Average pairs of columns in a matrix -


i have large matrix made of many columns. new matrix same number of rows , half number of columns averaging every nearby 2 columns (for example column 1 2, column 3 4, etc). i'm using loop, wondering whether there smarter way achieve this.

here's vectorized solution:

m <- matrix(1:96,8); m; ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] ## [1,]    1    9   17   25   33   41   49   57   65    73    81    89 ## [2,]    2   10   18   26   34   42   50   58   66    74    82    90 ## [3,]    3   11   19   27   35   43   51   59   67    75    83    91 ## [4,]    4   12   20   28   36   44   52   60   68    76    84    92 ## [5,]    5   13   21   29   37   45   53   61   69    77    85    93 ## [6,]    6   14   22   30   38   46   54   62   70    78    86    94 ## [7,]    7   15   23   31   39   47   55   63   71    79    87    95 ## [8,]    8   16   24   32   40   48   56   64   72    80    88    96 (m[,seq(1,ncol(m),2)]+m[,seq(2,ncol(m),2)])/2; ##      [,1] [,2] [,3] [,4] [,5] [,6] ## [1,]    5   21   37   53   69   85 ## [2,]    6   22   38   54   70   86 ## [3,]    7   23   39   55   71   87 ## [4,]    8   24   40   56   72   88 ## [5,]    9   25   41   57   73   89 ## [6,]   10   26   42   58   74   90 ## [7,]   11   27   43   59   75   91 ## [8,]   12   28   44   60   76   92 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -