Hi I have this function and this matrix: function(x,y) x+y/x m<-matrix(c(1,2,4,2,10,8),3,2)> m[,1] [,2] [1,] 1 2 [2,] 2 10 [3,] 4 8 each row represent a point (x,y) in a chart and I want via my fucntion to calculate the image in order to get this results: for point (1,2) I would get 1+2/1 = 3 for point (2,10) I would get 2+10/2 = 7 for point (4,8) I would get 4+8/4 = 6 I have tried using sapply here but I get this:> sapply(m,function(x,y) x+y/x)Error in y/x : 'y' is missing what I am doing wrong? thanks ADias -- View this message in context: http://r.789695.n4.nabble.com/matrix-and-a-function-apply-function-tp3254271p3254271.html Sent from the R help mailing list archive at Nabble.com.
On Feb 2, 2011, at 9:12 AM, ADias wrote:> > Hi > > I have this function and this matrix: > > function(x,y) x+y/x > > m<-matrix(c(1,2,4,2,10,8),3,2) > >> m > [,1] [,2] > [1,] 1 2 > [2,] 2 10 > [3,] 4 8 > > each row represent a point (x,y) in a chart and I want via my > fucntion to > calculate the image in order to get this results: > > for point (1,2) I would get 1+2/1 = 3 > for point (2,10) I would get 2+10/2 = 7 > for point (4,8) I would get 4+8/4 = 6 > > I have tried using sapply here but I get this: > >> sapply(m,function(x,y) x+y/x) > Error in y/x : 'y' is missingI'm not sure what sapply does with a matrix argument. I've only used t with vectors and lists. I suspect that it would straighten out the argument to a length = 6 vector. (And then, of course, the "y" wouldn't be there.)> > what I am doing wrong?Two things: instead use apply() and realize that the argument is passed as a vector apply(m, 1, function(x) x[1] +x[2]/x[1] ) -- David Winsemius, MD West Hartford, CT
there is no need for 'apply' here, because R can handle vectors. ord<-m[,1]+m[,2]/m[,1] Am 02.02.2011 15:12, schrieb ADias:> > Hi > > I have this function and this matrix: > > function(x,y) x+y/x > > m<-matrix(c(1,2,4,2,10,8),3,2) > >> m > [,1] [,2] > [1,] 1 2 > [2,] 2 10 > [3,] 4 8 > > each row represent a point (x,y) in a chart and I want via my fucntion to > calculate the image in order to get this results: > > for point (1,2) I would get 1+2/1 = 3 > for point (2,10) I would get 2+10/2 = 7 > for point (4,8) I would get 4+8/4 = 6 > > I have tried using sapply here but I get this: > >> sapply(m,function(x,y) x+y/x) > Error in y/x : 'y' is missing > > what I am doing wrong? > > thanks > ADias-- Eik Vettorazzi Institut f?r Medizinische Biometrie und Epidemiologie Universit?tsklinikum Hamburg-Eppendorf Martinistr. 52 20246 Hamburg T ++49/40/7410-58243 F ++49/40/7410-57790