Home > Software design >  For loop to get rowmeans of each 8 columns in a large dataframe
For loop to get rowmeans of each 8 columns in a large dataframe

Time:10-16

I have a large data.frame with 8 columns per sample with 200 samples. I need to get row-means of each 8.

rowMeans(mat[j,1:8]), rowMeans(mat[j,9:16]), rowMeans(mat[j,17:24])...

rownames are gene names. I used the following:

for(j in 1:nrow(mat)){
for (i in 1:ncol(mat)/8) {
row_m[j, i]<- rowMeans(mat[j,c(i:i 7)])
}
}

Dataframe sample data, here I have shown 9 columns, should get the mean from first 8 (AM) and then repeat for other samples....

dput(head(deconv3[1:9], 20)) structure(list(AM.amplifying.intestine = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), AM43.5.epithelial.of.mammary = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.76506, 0, 0, 1406.48, 0, 196.401, 0, 1996.5, 0), AM.epithelium.of.bronchus = c(549.649, 1647.63, 0, 0, 0, 0, 0, 0, 699.868, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), AM.epithelium.of.intestine = c(0, 0, 0, 0, 0, 0, 572.85, 59.2414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), AM.epithelium.of.trachea = c(0, 0, 0, 0, 199.549, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), AM.kidney.epithelial.cell = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.32926, 0, 0, 333.592, 0), AM.medullary.thymic.epithelial.cell = c(126.847, 0, 0, 0, 0, 0, 0, 0, 0, 63.1822, 0, 0, 0, 0, 0, 0, 0, 26.0598, 0, 11.117), AM.myoepithelial.cell = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), AK.amplifying.intestine = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c("A1BG", "A2M", "NAT2", "SERPINA3", "AANAT", "ABAT", "ABCA2", "ABCA3", "ABCB7", "ABCA4", "ABO", "ACACA", "ACADL", "ACADS", "ACADSB", "ACAT1", "ACLY", "ACR", "ACP1", "ACRV1"), class = "data.frame")

But it does not work. I am wondering if you could help me with this. Thanks in advance!

CodePudding user response:

sample_length <- 3
samples_per_row <- ncol(mat)/sample_length
row_m <- matrix(nrow=dim(mat)[1], ncol = samples_per_row)
for (j in 1:nrow(mat)) {
  k <- 1
  for (i in seq(from = 1,
                to = ncol(mat),
                by = sample_length)) {
    row_m[j, k] <- mean(as.numeric(mat[j, i:(i   (sample_length-1))]))
    k <- k   1
  }
}

CodePudding user response:

Try:

row_m <- do.call(cbind, lapply(1:(NCOL(mat) %/% 8   1), function(i){
  rowMeans(d[, ((1:NCOL(mat) - 1) %/% 8   1) == i, drop=F])})) 
  • Related