[R] writing a function

K. Elo maillists at nic.fi
Fri Feb 8 16:59:28 CET 2008


Hi Mohamed,

mohamed nur anisah wrote (8.2.2008):
> 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])
> }

This returns the value in row i, in column j, not the matrix. 
Replace 'return(w[i,k]) with just 'w'.

>   v<-function(n){          #function of a vector
>  y=vector(length=n)
>   for(i in 1:n){
>    y[i]=i
>   }
>  return(y[i])
> }

The same here: the function returns the value of the ith element in the 
vector. Again: Replace 'return(y[i]) with just 'y'.

Please compare the outputs:

> mm<-function(m,n) {
+  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])
+ }
> mm(5,10)
[1] 15

> mm<-function(m,n) {
+  w<-matrix(nrow=m, ncol=n)
+  for(i in 1:m) {
+   for(j in 1:n) {
+     w[i,j]=i+j
+   }
+  }
+ w
+ }
> mm(5,10)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    2    3    4    5    6    7    8    9   10    11
[2,]    3    4    5    6    7    8    9   10   11    12
[3,]    4    5    6    7    8    9   10   11   12    13
[4,]    5    6    7    8    9   10   11   12   13    14
[5,]    6    7    8    9   10   11   12   13   14    15

Kind regards,
Kimmo



More information about the R-help mailing list