# Re: [R] writing a function

From: Johannes Hüsing <johannes_at_huesing.name>
Date: Sun, 10 Feb 2008 12:14:59 +0100

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")

______________________________________________
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.
```
Received on Sun 10 Feb 2008 - 11:20:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 10 Feb 2008 - 11:30:13 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.