Sum every nth points

前端 未结 9 958
耶瑟儿~
耶瑟儿~ 2020-11-29 04:42

I have a vector and I need to sum every n numbers and return the results. This is the way I plan on doing it currently. Any better way to do this?



        
相关标签:
9条回答
  • 2020-11-29 05:23

    One way is to use rollapply from zoo:

    rollapply(v, width=n, FUN=sum, by=n)
    # [1]  55 155 255 355 455 555 655 755 855 955
    

    And in case length(v) is not a multiple of n:

    v <- 1:92
    
    rollapply(v, width=n, FUN=sum, by=n, partial=T, align="left")
    # [1]  55 155 255 355 455 555 655 755 855 183
    
    0 讨论(0)
  • 2020-11-29 05:25
    v <- 1:100
    
    n <- 10
    
    cutpoints <- seq( 1 , length( v ) , by = n )
    
    categories <- findInterval( 1:length( v ) , cutpoints )
    
    tapply( v , categories , sum )
    
    0 讨论(0)
  • 2020-11-29 05:36

    A little late to the party, but I don't see a rowsum() answer yet. rowsum() is proven more efficient than tapply() and I think it would also be very efficient relative to a few of the other responses as well.

    rowsum(v, rep(seq_len(length(v)/n), each=n))[,1]
    #  1   2   3   4   5   6   7   8   9  10 
    # 55 155 255 355 455 555 655 755 855 955
    

    Using @Josh O'Brien's grouping technique would likely improve efficiency even more.

    rowsum(v, (seq_along(v)-1) %/% n)[,1]
    #  0   1   2   3   4   5   6   7   8   9 
    # 55 155 255 355 455 555 655 755 855 955 
    

    Simply wrap in unname() to drop the group names.

    0 讨论(0)
提交回复
热议问题