[R] using matrix data for function

Liaw, Andy andy_liaw at merck.com
Wed Sep 17 20:46:33 CEST 2003


Don't think this is "best", but here's one way:

> mat <- matrix(1:12, 6)
> mat
     [,1] [,2]
[1,]    1    7
[2,]    2    8
[3,]    3    9
[4,]    4   10
[5,]    5   11
[6,]    6   12
> f <- function(x, y) x + y
> apply(mat, 1, function(x) do.call("f", as.list(x)))
[1]  8 10 12 14 16 18

Note that apply(mat, 1, f) won't work, because both values are passed to f
in a single vector.

Perhaps better alternatives are:

1. Re-write f so that it takes a single vector of two elements, or write a
wrapper fw <- function(x) f(x[1], x[2]), then use fw in apply().

2. Re-write f so that it's vectorized, so that f(mat[,1], fmat[,2]) works.

HTH,
Andy


> -----Original Message-----
> From: Bing Zhang [mailto:bih at ornl.gov] 
> Sent: Wednesday, September 17, 2003 2:03 PM
> To: r-help
> Subject: [R] using matrix data for function
> 
> 
> Hi All,
> 
> I have a function, f(x,y)
> I have a matrix of data, m,  with the 1st column is x and the 
> 2nd column is y What's the best way to get f(x,y) for each 
> row of the matrix? I tried 
> result<-f(m[,1],m[,2]) but it doesn't work.
> 
> Thanks!
> 
> Bing
> 
> ---------------------------------
> 1060 Commerce Park
> Oak Ridge National Laboratory
> P.O. Box 2008, MS 6480
> Oak Ridge, TN 37831-6480
> Phone: 865-241-0761
> Email: zhangb at ornl.gov
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://www.stat.math.ethz.ch/mailman/listinfo> /r-help
>




More information about the R-help mailing list