[R] using matrix data for function

Simon Fear Simon.Fear at synequanon.com
Thu Sep 18 13:04:35 CEST 2003


I think you will find the "new" (1.7.0) function

mapply(sum, mat[,1], mat[,2])

is an excellent generic approach (though in the particular
example, rowsum() would do the job).

I'd been waiting years for mapply(), love it!


> -----Original Message-----
> From: Liaw, Andy [mailto:andy_liaw at merck.com]
> Sent: 17 September 2003 19:47
> To: 'Bing Zhang'; r-help
> Subject: RE: [R] using matrix data for function
> 
> 
> Security Warning:
> If you are not sure an attachment is safe to open please contact 
> Andy on x234. There are 0 attachments with this message.
> ________________________________________________________________
> 
> 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
> >
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
 

Simon Fear
Senior Statistician
Syne qua non Ltd
Tel: +44 (0) 1379 644449
Fax: +44 (0) 1379 644445
email: Simon.Fear at synequanon.com
web: http://www.synequanon.com
 
Number of attachments included with this message: 0
 
This message (and any associated files) is confidential and\...{{dropped}}




More information about the R-help mailing list