[R] How to convert the output of tapply() so that it has the same order as the input?
Marius Hofert
marius.hofert at math.ethz.ch
Sat Sep 15 20:07:02 CEST 2012
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.
More information about the R-help
mailing list