How to create self cumulating vector in R -


i think easy r kung-fu weak. i'm trying create vector of in cumulative way. code works i'd more elegant , automated. have millions of rows need cumulated.

a <- c(4,4,5,1,9) <- a[order(-a[])] k <- a[1:length(a)]/sum(a) w <- c(k[1],k[1]+k[2],k[1]+k[2]+k[3],k[1]+k[2]+k[3]+k[4],k[1]+k[2]+k[3]+k[4]+k[5]) w 

did mean cumsum() ?

> <- c(4,4,5,1,9) > <- a[order(-a[])]            # calling sort shorter > k <- a[1:length(a)]/sum(a)     # long way   > k  [1] 0.391304 0.217391 0.173913 0.173913 0.043478 > k <- a/sum(a)                  # same, shorter > k   [1] 0.391304 0.217391 0.173913 0.173913 0.043478 > ck <- cumsum(k)  > ck   [1] 0.39130 0.60870 0.78261 0.95652 1.00000  >    

edit overlooked simplification:

> <- c(4,4,5,1,9) > ck <- cumsum( sort(a, decr=true) / sum(as) )  > ck   [1] 0.39130 0.60870 0.78261 0.95652 1.00000  >    

you want sort() here rather order() coupled indexing.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -