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

Michael Hannon jmhannon.ucdavis at gmail.com
Tue Oct 13 23:16:20 CEST 2015


The answer to "another note" is:

mapply(rep, w, 5:1)

I'll try to look at the first part in more detail later today.

-- Mike


On Mon, Oct 12, 2015 at 5:55 PM, Annie Hawk via R-help
<r-help at r-project.org> wrote:
> 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]]
>
> ______________________________________________
> 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