Re: [R] writing a function

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

mohamed nur anisah <> [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)




Johannes Hüsing               There is something fascinating about science. 
                              One gets such wholesale returns of conjecture  from such a trifling investment of fact.                (Mark Twain, "Life on the Mississippi")

______________________________________________ mailing list
PLEASE do read the posting guide
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 Please read the posting guide before posting to the list.

list of date sections of archive