Looping over a matrix into a matrix in R

Viewed 33

I want to calculate certain column means of different sets of rows from a dataframe/matrix and loop them into a new matrx/dataframe.

I have a df that looks like:

>mydf=as.data.frame(matrix(1:20, nrow = 10, ncol = 10))
>mydf=cbind(Sample_ID=c(rep("A",5), rep("B",5)), mydf)

>mydf
   Sample_ID V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1          A  1 11  1 11  1 11  1 11  1  11
2          A  2 12  2 12  2 12  2 12  2  12
3          A  3 13  3 13  3 13  3 13  3  13
4          A  4 14  4 14  4 14  4 14  4  14
5          A  5 15  5 15  5 15  5 15  5  15
6          B  6 16  6 16  6 16  6 16  6  16
7          B  7 17  7 17  7 17  7 17  7  17
8          B  8 18  8 18  8 18  8 18  8  18
9          B  9 19  9 19  9 19  9 19  9  19
10         B 10 20 10 20 10 20 10 20 10  20

Now I want all means of rows A [2:4,2:11] and all means of rows B [7:9,2:11] in a new 2 x 10 dataframe. That means, I want all rowmeans for rows 2:4 for each set of sample_IDs (col 1).

  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 3 13  3 13  3 13  3 13  3  13
2 8 18  8 18  8 18  8 18  8  18

My code looks like this:

 Means_genes <- matrix(nrow = length(unique(mydf$Sample_ID)), ncol = (length(mydf[1,])-1))
 for(i in mydf[!duplicated(mydf$Sample_ID), ]$Sample_ID){
 sample = mydf[mydf$Sample_ID == i, ]
  samplemean=colMeans(sample[2:4,2:length(sample[1,])])
   for (j in 1: length(unique(mydf$Sample_ID))){
    Means_genes[j,]=c(samplemean)}
 }

Which gives me the correct matrix size, but its only filled with the last loop of column means. Any help would be appreciated!

1 Answers

You can use by to split the data for each Sample_ID and calculate columnwise mean for rows 2-4 in each group.

result<- do.call(rbind, by(mydf[-1],mydf$Sample_ID,function(x) colMeans(x[2:4,])))

#  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#A  3 13  3 13  3 13  3 13  3  13
#B  8 18  8 18  8 18  8 18  8  18

Or with dplyr :

library(dplyr)

result <- mydf %>%
  group_by(Sample_ID) %>%
  slice(2:4) %>%
  summarise(across(V1:V10, mean)) %>%
  select(-Sample_ID)
Related