[R] matrix and a function - apply function
Petr PIKAL
petr.pikal at precheza.cz
Wed Feb 2 16:11:17 CET 2011
Hi
r-help-bounces at r-project.org napsal dne 02.02.2011 16:05:21:
>
> 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 missing
>
> I'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] )
Maybe apply is not necessary here
> m[,1]+m[,2]/m[,1]
[1] 3 7 6
Regards
Petr
>
>
> --
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list