[R] Breaking up a vector

Marc Schwartz marc_schwartz at me.com
Fri May 25 20:56:26 CEST 2012


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)

> str(x.mat)
 int [1:294, 1:7] 1 8 15 22 29 36 43 50 57 64 ...

> head(x.mat)
     [,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))}))


> str(Res)
 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"

> head(Res)
     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:

> Hello,
> 
> Tip: see the difference between the following two.
> 
> 
> for(i in 1:7)
> 	cat(i, ":", (i-1)*7:(i)*7, "\n")
> for(i in 1:7)
> 	cat(i, ":", ((i-1)*7):(i*7), "\n")
> 
> 
> (operator ':' has high precedence...)
> 
> Hope this helps,
> 
> Rui Barradas
> 
> AOLeary wrote
>> 
>> Hi all,
>> 
>> My problem is as follows: 
>> 
>> I want to run a loop which calculates two values and stores them in
>> vectors r and rv, respectively.
>> They're calculated from some vector x with length a multiple of 7.
>> 
>> x <- c(1:2058)
>> 
>> I need to difference the values but it would be incorrect to difference it
>> all in x, it has to be broken up first. I've tried the following:
>> 
>> r <- c(1:294)*0
>> rv <- c(1:294)*0
>> 
>> #RUN A LOOP WHERE YOU INPUT THE lx[(i-1)*7:i*7] INTO Z
>> for (i in 1:294){
>> #CREATE A NEW VECTOR OF LENGTH 7
>> z <- NULL
>> length(z)=7
>> dz <- NULL
>> dz2 <- NULL
>> 
>> #STORE THE VALUES IN z
>> z <- lx[1+(i-1)*7:(i)*7]
>> 
>> #THEN DIFFERENCE THOSE
>> #THIS IS r_t,i,m
>> dz=diff(z)
>> 
>> #SUM THIS UP AND STORE IT IN r, THIS IS r_t
>> r[i] <- sum(dz)
>> 
>> #SUM UP THE SQUARES AND STORE IT IN rv, THIS IS RV_t
>> dz2 <- dz^2
>> rv[i] <- sum(dz2)
>> #END THE LOOP
>> }
>> 
>> 
>> However, the window seems to expand for some reason, so z ends up being a
>> much longer vector than it should be and full of NAs.
>> 
>> 
>> Any help or advice is much appreciated.
>> 
>> Aodhán
>> 



More information about the R-help mailing list