aggregate(val~lvls+nm,data=x,FUN='median')
On Tue, Feb 28, 2012 at 4:43 PM, Ben quant <ccquant at gmail.com>
wrote:> Hello,
>
> I can get the median for each factor, but I'd like another column to go
> with each factor. The nm column is a long name for the lvls column. So
> unique work except for the order can get messed up.
>
> Example:
> x >
data.frame(val=1:10,lvls=c('cat2',rep("cat1",4),rep("cat2",4),'cat1'),nm=c('longname2',rep("longname1",4),rep("longname2",4),'longname1'))
> ?x
> val lvls ? ? ? ?nm
> 1 ? ?1 cat2 longname2
> 2 ? ?2 cat1 longname1
> 3 ? ?3 cat1 longname1
> 4 ? ?4 cat1 longname1
> 5 ? ?5 cat1 longname1
> 6 ? ?6 cat2 longname2
> 7 ? ?7 cat2 longname2
> 8 ? ?8 cat2 longname2
> 9 ? ?9 cat2 longname2
> 10 ?10 cat1 longname1
>
> unique doesn't work in data.frame:
> ?mdn = do.call(rbind,lapply(split(x[,1], x[,2]), median))
> ?data.frame(mdn,ln=as.character(unique(x[,3])))
> mdn ? ? ? ?ln
> cat1 ? 4 longname2
> cat2 ? 7 longname1
>
> I want:
> mdn ? ? ? ?ln
> cat1 ? 4 longname1
> cat2 ? 7 longname2
>
> Thank you very much!
>
> PS - looking for simple'ish solutions. I know I can do it with loops
and
> merges, but is there an option I am not using here?
>
> Ben
>
> ? ? ? ?[[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.