# Array position to matrix coordinates conversion

May 30, 2011
By

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

`#A function that is sometimes useful in determining the #coordinate(i.e. row and column number) of a matrix position#(and vice-versa). #Either a vector of positions ("pos") #OR a 2 column matrix of matrix coordinates, ("coord", i.e. cbind(row,col)), #AND the matrix dimentions must be supplied (dim.mat, i.e. c(nrow,ncol)).pos2coord<-function(pos=NULL, coord=NULL, dim.mat=NULL){ if(is.null(pos) & is.null(coord) | is.null(dim.mat)){  stop("must supply either 'pos' or 'coord', and 'dim.mat'") } if(is.null(pos) & !is.null(coord) & !is.null(dim.mat)){  pos <- ((coord[,2]-1)*dim.mat)+coord[,1]   return(pos) } if(!is.null(pos) & is.null(coord) & !is.null(dim.mat)){  coord <- matrix(NA, nrow=length(pos), ncol=2)  coord[,1] <- ((pos-1) %% dim.mat) +1  coord[,2] <- ((pos-1) %/% dim.mat) +1  return(coord) }}`

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Tags: , , ,