[R] writing a function
Johannes Hüsing
johannes at huesing.name
Sun Feb 10 12:14:59 CET 2008
mohamed nur anisah <nuranisah_mohamed at yahoo.com> [Fri, Feb 08, 2008 at 04:42:41PM CET]:
> Dear lists,
>
> I'm in my process of learning of writing a function. I tried to write a simple functions of a matrix and a vector. Here are the codes:
>
> mm<-function(m,n){ #matrix function
> w<-matrix(nrow=m, ncol=n)
> for(i in 1:m){
> for(j in 1:n){
> w[i,j]=i+j
> }
> }
> return(w[i,j])
> }
>
In addition to the other comments, allow me to remark that
R provides a lot of convenience functions on vectors that
make explicit looping unnecessary. An error such as yours
wouldn't have occurred to a more experienced expRt because
indices wouldn't turn up in the code at all:
mm <- function(m, n) {
a <- array(nrow=m, ncol=n)
row(a)+col(a)
}
Greetings
Johannes
--
Johannes Hüsing There is something fascinating about science.
One gets such wholesale returns of conjecture
mailto:johannes at huesing.name from such a trifling investment of fact.
http://derwisch.wikidot.com (Mark Twain, "Life on the Mississippi")
More information about the R-help
mailing list