[R] Xapply question
Claudia Beleites
cbeleites at units.it
Fri Nov 12 14:46:19 CET 2010
Dear list,
I'm stuck with looking for a function of the *apply family, which I suppose
exists already – just I can't find it:
What I'm looking for is somewhere between sweep and mapply that does a
calculation vectorized over a matrix and a vector:
It should work complementary to sweep: for each row of the matrix, a different
value of the vector should be handed over.
Close to mapply because I need to go through different variables in a parallel
fashion (at the moment a matrix and a vector).
Kind of a mapply that hands over array slices.
Maybe it is easiest with an example. This loop does what I want, but
> A <- matrix (rnorm (12), 3)
> A
[,1] [,2] [,3] [,4]
[1,] 0.1286 0.2888 -0.4435 -0.90966
[2,] -1.6000 -1.0884 1.3736 0.07754
[3,] 0.4581 1.5413 0.6133 -0.12131
> v <- 1 : 3
> f <- function (x, y) { # some function depending on vector x and skalar y
+ c (sum (x^2), y)
+ }
> result <- matrix (NA, nrow = nrow (A), ncol = 2)
> for (r in 1 : nrow (A))
+ result [r,] <- f (A [r,], v [r])
> result
[,1] [,2]
[1,] 1.124 1
[2,] 5.637 2
[3,] 2.976 3
The matrix will easily be in the range of 1e4 - 1e5 rows x 1e2 - 1e3 columns, so
I do not want to split it into a list and combine it afterwards.
The reason why I ask for a function is partly also because I want to overload
the functionality for a specific class and I don't think it's a good idea to
invent a name for something that probably already exists.
If this function does not exist, any ideas how I should call it?
Thanks a lot,
Claudia
--
Claudia Beleites
Dipartimento dei Materiali e delle Risorse Naturali
Università degli Studi di Trieste
Via Alfonso Valerio 6/a
I-34127 Trieste
phone: +39 0 40 5 58-37 68
email: cbeleites at units.it
More information about the R-help
mailing list