[R] loops in R

Daniel Nordlund djnordlund at frontier.com
Wed Nov 5 19:12:33 CET 2014


On 11/5/2014 5:41 AM, Noha Osman wrote:
> Hi Folks
>
> Iam  a new user of R and I have a question . Hopefully anyone help me in that issue
>
>
> I have that dataset as following
>
>   Sample      Population  Species  Tissue         R         G        B
> 1 Bari1_062-1      Bari1     ret   seed  94.52303  80.70346 67.91760
> 2 Bari1_062-2      Bari1     ret   seed  98.27683  82.68690 68.55485
> 3 Bari1_062-3      Bari1     ret   seed 100.53170  86.56411 73.27528
> 4 Bari1_062-4      Bari1     ret   seed  96.65940  84.09197 72.05974
> 5 Bari1_062-5      Bari1     ret   seed 117.62474  98.49354 84.65656
> 6 Bari1_063-1      Bari1     ret   seed 144.39547 113.76170 99.95633
>
> and I have 20 populations as following
>
> [1] Bari1      Bari2      Bari3      Besev      Cermik     Cudi       Derici     Destek     Egil
> [10] Gunasan    Kalkan     Karabace   Kayatepe   Kesentas   Ortanca    Oyali      Cultivated Sarikaya
> [19] Savur      Sirnak
>
> I need to calculate mean and variance of each population using column [R] using  for-loop
>
>
> Thanks
>

You don't want to use loops here, but rather some vectorized function. 
One possibility is some thing like the following:

with(your_data_frame,aggregate(R,list(Population), mean))
with(your_data_frame,aggregate(R,list(Population), var))

hope this is helpful,

Dan

Daniel Nordlund
Bothell, WA  USA



More information about the R-help mailing list