2

I have a matrix with many columns that need to be combined separately. I want to combine them and take the means across rows and then put them into a new matrix. TYIA

I have a matrix called data like this:

    p7.1    p7.2    p7.3    p8.1   p8.2    p9.1   p9.2
1    0      1       0       4      5       2      1
2    15     6        2       3      4       10    1
3     1     2        4       5      1       0      2

This is my desired result: All "p7" should be in one column with the value of the mean of the rows of all sep. p7 values.

      p7            p8          p9
1     .5            4.5         1.5
2     11.5          3.5         5.5
3     3.5           3            1

I am able to execute this by saving p7, p8, p9 to different variables like this: p7 <- apply(data[,1:3], 1, mean) etc. However, I'm struggling to find a more concise way to do this. Perhaps a for loop, but I have not been able to successfully do this.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
jimuq233
  • 53
  • 4

1 Answers1

3

We can try the code below

do.call(
  cbind,
  Map(rowMeans, split.default(df, gsub("\\..*", "", names(df))))
)

and we will obtain

         p7  p8  p9
1 0.3333333 4.5 1.5
2 7.6666667 3.5 5.5
3 2.3333333 3.0 1.0

Data

> dput(df)
structure(list(p7.1 = c(0L, 15L, 1L), p7.2 = c(1L, 6L, 2L), p7.3 = c(0L, 
2L, 4L), p8.1 = c(4L, 3L, 5L), p8.2 = c(5L, 4L, 1L), p9.1 = c(2L,
10L, 0L), p9.2 = c(1L, 1L, 2L)), class = "data.frame", row.names = c("1",
"2", "3"))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81