[R] Create variables with common values for each group
Dieter Menne
dieter.menne at menne-biomed.de
Tue Jun 20 11:03:39 CEST 2006
Stephan Lindner <lindners <at> umich.edu> writes:
> The problem is to create new variables from a data frame which
> contains both individual and group variables, such as mean age for an
> household. My data frame:
>
> df
>
> hhid h.age
> 1 10010020 23
> 2 10010020 23
...
> where hhid is the same number for each household, h.age the age for
> each household member.
>
> I tried tapply, by(), and aggregate. The best I could get was:
>
> by(df, df$hhid, function(subset) rep(mean(subset$h.age,na.rm=T),nrow(subset)))
>
> df$hhid: 10010020
> [1] 23 23
> ------------------------------------------------------------
> df$hhid: 10010126
> [1] 51 51
try something like
do.call("rbind",byresult)
As you did not provide a running example, the suggestion is only approximately
correct.
Dieter
More information about the R-help
mailing list