[R] How to convert the output of tapply() so that it has the same order as the input?

William Dunlap wdunlap at tibco.com
Sat Sep 15 20:31:55 CEST 2012


Does ave() do what you want?
  y. <- ave(x$value, x$x1, x$x2, FUN=function(x)x)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Marius Hofert
> Sent: Saturday, September 15, 2012 11:07 AM
> To: R-help
> Subject: [R] How to convert the output of tapply() so that it has the same order as the
> input?
> 
> Hi,
> 
> I try to apply a function to subsets of a data.frame. tapply() does the job, but
> the as output, I am looking for a vector (not an array/matrix) ordered in the
> same way as the original data, so I can simply cbind the result to the original
> data.frame. Below is a minimal example.
> 
> I know that there are packages that can do these things easier, but I'm looking
> for a fast solution not requiring additional packages.
> 
> Cheers,
> 
> Marius
> 
> 
> ## data.frame
> set.seed(1)
> (x <- data.frame(x1=LETTERS[1:4], x2=1:2, value=runif(8)))
> 
> ## apply a function to each subset combination of x1 and x2
> y <- tapply(x$value, x[,-3], function(x) x)
> 
> ## (trials of) transforming the output to be of the same type and order as x$value
> (y. <- do.call(rbind, y)) # => wrong order
> (y. <- do.call(cbind, y)) # => wrong order
> 
> ## appending (that's the goal)
> z <- x
> z$value <- y.
> 
> ______________________________________________
> 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.




More information about the R-help mailing list