-----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.