[R] how to do away for loop using functionals?

Annie Hawk ahawk14 at yahoo.com
Tue Oct 13 02:55:42 CEST 2015


HI R-experts, 


I am trying to speed up my calculation of the A results below and replace the for loop withsome functionals like lapply.  After manyreadings, trial and error, I still have no success.  Would anyone please give me some hints onthat?  

Thank you in advance.

Anne 


The program is this, I have a complicated function and itneeds to operate on some subsets of a dataset many times, depending on thevalues of group.  I simplify the functionand dataset for this example run.  

getResult <- function(d) {

      #examplefunction

     weighted.mean(x=d[,1], w=d[,2]) 

}


 
#example data setup

n=20; 

set.seed(1)

g=rep(1:5,each=4)

df=as.data.frame(cbind( sort(rnorm(mean=15,sd=10, n)),runif(n), rbinom(n, 1, 0.4) , g )); df

getResult(df)

i0=c(1,2,4,5,5)

ng= length(unique(g))


 
#initiation of result matrix

A=matrix(Inf, ng, ng); A

for(i in 1:ng) 

{              cat("i:",i,"")

                for(jin i0[i]:ng) {

                                ok= !is.na(match(g,i:j)); cat("j:",j,"\n"); 

                                A[i,j]=getResult(d=df[ok,])

                } #endfor (j)

} #end for (i)

Is there an elegant way to remove the for loop here?  I try to make it flat for faster run but Icannot figure out how to subset the observations faster without error to apply the functiongetResult.  Any hint is appreciated.


 

 
on another note, is there a more elegant way to initiate the list as follows?

mylist=list(); w=rep(4,5)

for (i in 1:5) mylist[[i]]=w[i:5]


 

	[[alternative HTML version deleted]]



More information about the R-help mailing list