Skip to content
Prev 295663 / 398502 Next

Breaking up a vector

Just to throw out another approach to the underlying problem.

Since the original vector length is an integer multiple of 7, taking the 'whole object' approach that is intrinsic to R, one can convert the vector to a 7 column matrix and then use apply() to run the entire process on each 7 element row in the matrix using the proverbial single line of R code.

x <- 1:2058 # or seq(2058)

x.mat <- matrix(x, ncol = 7, byrow = TRUE)
int [1:294, 1:7] 1 8 15 22 29 36 43 50 57 64 ...
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    2    3    4    5    6    7
[2,]    8    9   10   11   12   13   14
[3,]   15   16   17   18   19   20   21
[4,]   22   23   24   25   26   27   28
[5,]   29   30   31   32   33   34   35
[6,]   36   37   38   39   40   41   42


Res <- t(apply(x.mat, 1, function(x) {dz <- diff(x); c(r = sum(dz), rv = sum(dz^2))}))
num [1:294, 1:2] 6 6 6 6 6 6 6 6 6 6 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "r" "rv"
r rv
[1,] 6  6
[2,] 6  6
[3,] 6  6
[4,] 6  6
[5,] 6  6
[6,] 6  6


So you end up with a two column matrix containing the r and rv values in each row, for each 7 element segment of the original x.

Regards,

Marc Schwartz
On May 25, 2012, at 10:56 AM, Rui Barradas wrote: