Sum every nth points

前端 未结 9 1110
耶瑟儿~
耶瑟儿~ 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:17

    Update

    The olde version don't work. Here a ne awnser that use rep to create the grouping factor. No need to use cut:

    n <- 5 
    vv <- sample(1:1000,100)
    seqs <- seq_along(vv)
    tapply(vv,rep(seqs,each=n)[seqs],FUN=sum)
    

    You can use tapply

    tapply(1:100,cut(1:100,10),FUN=sum)
    

    or to get a list

    by(1:100,cut(1:100,10),FUN=sum)
    

    EDIT

    In case you have 1:92, you can replace your cut by this :

    cut(1:92,seq(1,92,10),include.lowest=T)
    

提交回复
热议问题