[R] function to reduce resolution of a vector or matrix?

peter dalgaard pdalgd at gmail.com
Wed Jun 8 09:39:37 CEST 2011


On Jun 3, 2011, at 17:42 , Carl Witthoft wrote:

> Hi,
> I feel dumb even asking, but isn't there an R function somewhere that I can use to reduce the resolution of a vector (or matrix) by summing terms in uniform blocks?  That is, for a vector X, reduce it to some X.short as  X.short[1]<- sum(X[1:10]);  X.short[2] <- sum(X[11:20]), and so on.
> 
> I did the following:
> 
> X.short<-colSums(matrix(X,16,2048/16)) # X is of length 2048
> 
> but surely there's already  a function somewhere that does this in a more general case?  And, my approach will get a bit painful for reducing a matrix in both dimensions.

aggregate.ts, but then you need to convert to "ts" and back. I'd likely go for 

tapply(X, (seq_along(X) - 1) %/% N, sum)

> x
 [1]  1  1  0 -1  1 -1  0  0  1 -2  1  0  0 -1  1
> as.numeric(aggregate(ts(x, frequency=3), 1, sum))
[1]  2 -1  1 -1  0
> tapply(x, (seq_along(x) - 1) %/% 3, sum)
 0  1  2  3  4 
 2 -1  1 -1  0 



-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list