Skip to content
Prev 361582 / 398502 Next

apply and cousins

Hi John,
With due respect to the other respondents, here is something that might help:

# get a vector of values
foo<-rnorm(100)
# get a vector of increasing indices (aka your "recent" values)
bar<-sort(sample(1:100,40))
# write a function to "clump" the adjacent index values
clump_adj_int<-function(x) {
 index_list<-list(x[1])
 list_index<-1
 for(i in 2:length(x)) {
  if(x[i]==x[i-1]+1)
   index_list[[list_index]]<-c(index_list[[list_index]],x[i])
  else {
   list_index<-list_index+1
   index_list[[list_index]]<-x[i]
  }
 }
 return(index_list)
}
index_clumps<-clump_adj_int(bar)
# write another function to sum the values
sum_subsets<-function(indices,vector) return(sum(vector[indices],na.rm=TRUE))
# now "apply" the function to the list of indices
lapply(index_clumps,sum_subsets,foo)

Jim


On Thu, Jun 9, 2016 at 2:41 AM, John Logsdon
<j.logsdon at quantex-research.com> wrote: