[R] sum of grouped elements of vector
Jim Lemon
drjimlemon at gmail.com
Fri Jan 23 10:14:02 CET 2015
Hi Kathryn,
I think this might do the trick:
make_group_sums<-function(x,maxgroups) {
lenx<-length(x)
runlengths<-sample(1:lenx,1)
for(i in 2:(maxgroups-1)) {
lenx<-lenx-runlengths[i-1]
runlengths[i]<-ifelse(lenx,sample(1:lenx,1),0)
}
runlengths[maxgroups]<-length(x)-sum(runlengths)
groups<-rep(1:maxgroups,runlengths)
groupsums<-by(x,groups,sum)
return(as.vector(groupsums))
}
Jim
On Fri, Jan 23, 2015 at 7:45 PM, Kathryn Lord
<kathryn.lord2000 at gmail.com> wrote:
> Dear R users,
>
> I have a quick quesiton.
>
> Here is a vector "a".
>
> a<- c(1,2,3,4,5,6,7,8).
>
> (In fact, I have a huge vector.)
>
>
> With "a", I'd like to create new vectors, for example,
>
> new1 = (1+2, 3, 4+5+6, 7+8)
> new2 = (1, 2+3+4+5+6+7, 8)
> new3 = (1+2+3+4+5+6+7, 8)
>
>
> How could I make the above vectors using R?
>
>
> Any suggestion will be greatly appreciated.
>
> Best,
>
> Kathryn Lord
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list