dimanche 14 janvier 2018

Modify a matrix by summing specific rows into a new row

I have a large data matrix of 2289 rows. A sample picture is attached. The matrix is called speciesTraps. All column values are numeric. I need to aggregate any rows to the previous row if speciesTraps[,1] is equal to zero. After reading other people's question and answers, I was thinking of creating a loop to do this with the following statement:

for (i in 1:nrow(subsetTrapsplusid)) {
row <- subsetTrapplusid [i,] 
if (subsetTrapsplusid[[1]]=0) {
print(aggregate(subsetTrapsplusid[row,], subsetTrapsplusid[(row-  1),],sum))
                            } 
else {(print (subsetTrapsplusid[i,])) 
  }
                            }

Please let me know if you have a suggestion.

screenshot of datamatrix

Aucun commentaire:

Enregistrer un commentaire