[R] how to rewrite this for loops in matrix form without loop

Joshua Wiley jwiley.psych at gmail.com
Mon May 3 19:37:19 CEST 2010


I believe you are trying to find the mean of x0 for each level (group) of y0.

try this:

by(x0, y0, mean)

or if you want a vector (e.g., to merge into a matrix)

c(by(x0, y0, mean))

Best regards,

Josh

On Mon, May 3, 2010 at 10:11 AM, song song <rprojecthelp at gmail.com> wrote:
> x0=rnorm(100)
> y0=rpois(100,3)+1
>
> ind=as.data.frame(table(y0))
>
> ind1=ind[,1]
> ind2=ind[,2]
>
> phi=NULL
> for (i in 1:length(ind2)){
>   phi[i]=sum(x0[y0==ind1[i]])/ind2[i]
> }
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Joshua Wiley
Senior in Psychology
University of California, Riverside
http://www.joshuawiley.com/



More information about the R-help mailing list