# [R] Learn Vectorization (Vectorize)

Alaios alaios at yahoo.com
Tue Jan 25 16:29:48 CET 2011

```Greetings Friends,
I would be grateful if you can help me undestand how to make my R code more efficiently.

I have read in R intoductory tutorial that a for loop is not used so ofter (and is not maybe not that efficient) compared to other languages.

So I am trying to build understanding how to get the equivalent of a for loop using more R-oriented thinking.

If I got it right one way to do that in R is Vectorize. So I have writen a small snippet of code with two nested for loops. I would be grateful if you can help me find the equivalent of this code using Vectorize (or any other R thinking)

My code takes as input a n*m matrix and prints the x,y coordinates where a cells starts and ends.

remap <- function (sr){
# Input this funcion takes as arguments
# sr: map
startpos<- -1 #
endpos<- +1 #
stepx<- (endpos - (startpos)) / nrow(sr)
stepy<- (endpos - (startpos)) / ncol(sr)

for (i in seq(from=-1,to=1,by=stepx) ) {
for (j in seq(from=-1,to=1,by=stepx) ){
cat(' \n',i,j)
}

}
}
sr<-matrix(data=seq(from=1,to=9),nrow=3,ncol=3,byrow=TRUE)
remap(sr)

Regards
Alex

```