Array position to matrix coordinates conversion

May 30, 2011
By

(This article was first published on me nugget, and kindly contributed to R-bloggers)

#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[1])+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]) +1
coord[,2] <- ((pos-1) %/% dim.mat[1]) +1
return(coord)
}
}
Created by Pretty R at inside-R.org

To leave a comment for the author, please follow the link and comment on his blog: me nugget.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.