[R] Question: Beginner stuck in a R cycle

Giovanni Petris GPetris at uark.edu
Wed Jul 9 00:28:15 CEST 2008


Hi Daniela,

There may be other more elegant ways of doing it, but here is one: 

> myD <- data.frame(code = sample(3, 10, rep = T), prev = rnorm(10), Pr_mean = 0)
> myD
   code        prev Pr_mean
1     3 -0.06710968       0
2     2 -1.43422034       0
3     1  0.22717580       0
4     3  0.32703754       0
5     3  1.26254159       0
6     2  0.65104107       0
7     1 -0.74293152       0
8     3  0.45845330       0
9     2 -0.64206400       0
10    3 -0.48671646       0
> m <- tapply(myD$prev, myD$code, mean)
> myD$Pr_mean <- m[match(myD$code, names(m))]
> myD
   code        prev    Pr_mean
1     3 -0.06710968  0.2988413
2     2 -1.43422034 -0.4750811
3     1  0.22717580 -0.2578779
4     3  0.32703754  0.2988413
5     3  1.26254159  0.2988413
6     2  0.65104107 -0.4750811
7     1 -0.74293152 -0.2578779
8     3  0.45845330  0.2988413
9     2 -0.64206400 -0.4750811
10    3 -0.48671646  0.2988413

Hope this helps.

Ciao,
Giovanni

> Date: Tue, 08 Jul 2008 13:18:13 +0000 (GMT)
> From: Daniela Ottaviani <d.ottaviani at yahoo.it>
> Sender: r-help-bounces at r-project.org
> Precedence: list
> DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=s1024; d=yahoo.it;
> 
> Dear All,
> 
> I have a database of 200 observations named myD.
> In the dataframe there are a column named code (with codes varying from 1 to 77), a column named "prevalence" with some quantitative measurements are given and an column named Pr_mean, with no values.
> 
> I would like to set a cycle to compute the average of prevalence values for each different code and store the averages under the empty field Pr_mean.
> 
> This is what I wrote:
> 
> # Set a cycle
> for (i in 1:nrow(myD)) {
> mycode = myD$code[i]
> mymean[i] = mean(prevalence)
> myD$Pr_mean[i] = mymean[i]
> }
> 
> With the above cycle I am able to compute the average of all 200 observations which is then written in every cell.
> I understand that a condition is missing, that indicates that the average has to be computed amongst the observations showing  the same codes values.
> 
> Could you please help me ?
> 
> 
> D.
> 
> 
> 
>       Posta, news, sport, oroscopo: tutto in una sola pagina. 
> Crea l&#39;home page che piace a te!
> www.yahoo.it/latuapagina
> 	[[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.
> 
> 

-- 

Giovanni Petris  <GPetris at uark.edu>
Department of Mathematical Sciences
University of Arkansas - Fayetteville, AR 72701
Ph: (479) 575-6324, 575-8630 (fax)
http://definetti.uark.edu/~gpetris/



More information about the R-help mailing list