Transforming a matrix into a partial averages one
I have a 320*25 matrix that I want to transform into a 64*25 matrix in this way: each row of the new matrix should have the averages of every 5 rows of the old one (and then they will be normalized by a certain vector in a similar way). Below you c开发者_JS百科an see how I've been trying to implement this:
for (x in c(1:64)){
helping.matrix[x,] = colSums(original.matrix[((5*(x-1)+1):5*x),])/sum(vector[((5*(x- 1)+1):5*x)])
}
Unfortunately this didn't work, returning the following error:
Error in inherits(x, "data.frame") : subscript out of bounds
There are a number of problems with the way you've tried to impliment this. First, it helps to make the example reproducible:
original.matrix <- matrix(1:(320*25), nrow=320, ncol=25)
Second, if you are going to use a for-loop, you need to initialize an object to hold the results:
helping.matrix <- matrix(nrow=64, ncol=25)
OK, now let's take a look at your code.
for (x in c(1:64)){
helping.matrix[x,] = colSums(original.matrix[((5*(x-1)+1):5*x),])/
The indexing expression here is pretty wild, and does not do what you want it to. For example, when x = 2, (5*(x-1)+1):5*x
= 12, 10. That doesn't match with your stated goal. at x = 9 the expression returns values greater than the number of rows in original.matrix, which is why you get the "out of bounds" error. The next problem occures when we get to
vector[((5*(x-1)+1):5*x)])
Here you are trying to index vector
as though it were a data object. But vector is not a data object, it is a function. Maybe you want c((5*(x-1)+1):5*x)
? Anyway it's not clear from your question exactly what this secton of code is intended to do, so I can't really offer much in the way of suggestions here.
OK, so let's make a fresh start. The way I would approach this problem is by making an index vector that maps on the the groups you want to apply your summing function to:
groups <- rep(1:(320/5), each=5)
Next, use a loop or an apply-family function to iterate over the groups. The for-loop approach would look something like
helping.matrix <- matrix(nrow=64, ncol=25)
for(i in unique(groups)) {
helping.matrix[i,] <- colSums(original.matrix[groups == i,])
}
and the apply-based approach would look like
helping.matrix <- Reduce(rbind, by(original.matrix, groups, colSums))
I've left out the part that is supposed to "normalized by a certain vector" because it's not clear to me what is actually supposed to happen there.
Well, this might do it - if you have numeric values without NA:s...
m <- matrix(runif(320*25),320)
k <- 5
m2 <- rowsum(m, rep(seq(nrow(m)/k), each=k))/k
精彩评论