[R] Window on a vector

Petr Savicky savicky at cs.cas.cz
Mon Mar 12 16:50:01 CET 2012


On Sat, Mar 10, 2012 at 04:44:00AM -0800, Alaios wrote:
> Dear all,
> I have a large vector (lets call it myVector) and I want to plot its value with the logic below
> 
> yaxis<-myVector[1]
> yaxis<-c(xaxis,mean(myvector[2:3])
> yaxis<-c(xaxis,mean(myvector[4:8])
> yaxis<c(xaxis,mean(myvector[9:16])
> yaxis<c(xaxis,mean(myvector[17:32])
> 
> this has to stop when the new ..... yaxis<c(xaxis,mean(myvector[1024:2048]) will not find the correspondent number of elements, either wise it will stop with an error.

Hi.

For computing the means, try something like the following

  myVector <- 50:100
  ilog <- floor(log2(1:length(myVector)))
  tapply(myVector, ilog, FUN = mean)

     0    1    2    3    4    5 
  50.0 51.5 54.5 60.5 72.5 90.5 

Compare with

  c(mean(myVector[1]), mean(myVector[2:3]), mean(myVector[4:7]), mean(myVector[8:15]),
    mean(myVector[16:31]), mean(myVector[32:51]))

  [1] 50.0 51.5 54.5 60.5 72.5 90.5

If you mean intervals, which end in a power of two, try

  ilog <- ceiling(log2(1:length(myVector)))
  tapply(myVector, ilog, FUN = mean)

     0    1    2    3    4    5    6 
  50.0 51.0 52.5 55.5 61.5 73.5 91.0 

  c(mean(myVector[1]), mean(myVector[2]), mean(myVector[3:4]), mean(myVector[5:8]),
    mean(myVector[9:16]), mean(myVector[17:32]), mean(myVector[33:51]))

  [1] 50.0 51.0 52.5 55.5 61.5 73.5 91.0

Hope this helps.

Petr Savicky.



More information about the R-help mailing list