[R] Double And average a vector

Petr Savicky savicky at cs.cas.cz
Sat Mar 24 12:25:35 CET 2012


On Sat, Mar 24, 2012 at 03:49:28AM -0700, Alaios wrote:
> Dear all,
> I am reading with R some measurements vectors from an external device.
> The length of each vector (containing numbers) is not constant.
> 
> I would like by doubling the numbers of elements I select to shrink the vector to a new one
> 
> Let's call the vector I read from the device as oldvector 
> 
> 
> and the shrinked version of it as newVersion
> 
> I want to have
> newVersion[1]<- mean(oldvector[1])
> newVersion[2]<- mean(oldvector[2:3])
> newVersion[3]<- mean(oldvector[4:7])
> newVersion[4]<- mean(oldvector[8:15])
> 
> as I said the length of oldvector is not the same sol it might be also the case that the last window will not find the corresponding number of elements.
> 
> How I can handle that in R?

Hi.

You asked a similar question at

  https://stat.ethz.ch/pipermail/r-help/2012-March/306188.html

The current formulation is more accurate. Let me recall one of
the previous solutions suitable for the current situation

  oldvector <- 1:20
  ilog <- floor(log2(1:length(oldvector)))
  ilog

  [1] 0 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4
  
  newVersion <- unname(tapply(oldvector, ilog, FUN = mean))
  newVersion

  [1]  1.0  2.5  5.5 11.5 18.0

Here, newVersion[1] is mean(oldvector[which(ilog == 0)]), where

 which(ilog == 0) # [1] 1

newVersion[1] is mean(oldvector[which(ilog == 1)]), where

  which(ilog == 1) # [1] 2 3

also

  which(ilog == 2) # [1] 4 5 6 7
  which(ilog == 3) # [1]  8  9 10 11 12 13 14 15
  which(ilog == 4) # [1] 16 17 18 19 20

The last group ends at 20, so it is smaller than the previous one.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list