take the mean of rows in a matrix r

前端 未结 3 640
轮回少年
轮回少年 2021-01-14 10:12

I have the following matrix of depth and temperature data (855 rows, 2 col) and would like to take the mean of every 3 rows within each column. For example:

         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 10:41

    Try to use tapply and apply:

    R > f <- rep(c(1:3), each = 3)
    R > f
    [1] 1 1 1 2 2 2 3 3 3
    R > x <- matrix(1:27, 9, 3)
    R > x
          [,1] [,2] [,3]
     [1,]    1   10   19
     [2,]    2   11   20
     [3,]    3   12   21
     [4,]    4   13   22
     [5,]    5   14   23
     [6,]    6   15   24
     [7,]    7   16   25
     [8,]    8   17   26
     [9,]    9   18   27
    R > apply(x, 2, function(t) tapply(t, f, mean))
      [,1] [,2] [,3]
    1    2   11   20
    2    5   14   23
    3    8   17   26
    

提交回复
热议问题