[R] writing a function

Bob Flagg bob at calcworks.net
Fri Feb 8 16:53:32 CET 2008


Anisah,

You just need to omit the indices in the return statements:


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
  		}
 	}
	w
}

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

On Fri, 2008-02-08 at 07:42 -0800, mohamed nur anisah wrote:
> 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])
> }
>    
>   v<-function(n){          #function of a vector
>  y=vector(length=n)
>   for(i in 1:n){
>    y[i]=i
>   }
>  return(y[i])
> }
>  
>   when i tried called on my matrix function; say mm(5,10). what i got is the single value of 15..where's is my matrix?? same thing happened to my vector function. Please help me figure out these problems. Thanks a bunch!!
>    
>   Cheers, 
>   Anisah
>    
>    
>    
> 
> 
> 
>        
> ---------------------------------
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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