[R] Question: Beginner stuck in a R cycle
(Ted Harding)
Ted.Harding at manchester.ac.uk
Tue Jul 8 18:01:40 CEST 2008
On 08-Jul-08 13:18:13, Daniela Ottaviani wrote:
> 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.
I think something on the following lines would do what you want
(I think it is wise to call the final column "Pr.mean", as below,
rather than "Pr_mean"):
for( Code in unique(myD$code) ){
ix <- (myD$code == Code )
myD$Pr.mean[ix] <- mean(myD$prevalence[ix])
}
Ted.
> 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'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.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 08-Jul-08 Time: 17:01:38
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list