r - bin/group numeric vectors of different length -


i have numeric vectors different lengths, ranging 300 500. 'normalize' them length of 100, i.e. vector of length 300 take mean of 3 values, vector of length 500 mean of 5 values , on.

how can bin numeric vectors , calculate mean without reordering? have not been successful cut far.

# numeric vectors of different lengths v1 = rnorm(300) v2 = rnorm(500)  # goal: numeric vectors of same length v1.binned = c(mean(v1[1],v1[2],v1[3]), ...) v2.binned = c(mean(v2[1],v2[2],v2[3], v2[4], v2[5]), ...) 

you can convert vectors matrix , use colmeans:

colmeans(matrix(v1,100)) [1] -0.09583398  0.01330998  0.11107002 colmeans(matrix(v2,100)) [1] -0.02396420  0.08638535 -0.03953273  0.09861287  0.01112838 

though beware of recycling if cut size not exact multiple of vector size. in case, split-sapply strategy job:

sapply(split(v1,(seq_along(v1)-1)%/%200),mean)         0         1  -0.041262  0.111070  

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -