How to create adjacency matrix from grid coordinates in R? -


i'm new site. wondering if had experience turning list of grid coordinates (shown in example code below df). i've written function can handle job small data sets run time increases exponentially size of data set increases (i think 800 pixels take 25 hours). it's because of nested loops don't know how around it.

## dummy data x <- c(1,1,2,2,2,3,3) y <- c(3,4,2,3,4,1,2) df <- as.data.frame(cbind(x,y)) df  ## here's looks image <- c(na,na,1,1) b <- c(na,1,1,1) c <- c(1,1,na,na) image <- cbind(a,b,c) f <- function(m) t(m)[,nrow(m):1] image(f(image))  ## here's adjacency matrix function that's slowwwwww adjacency.coordinates <- function(x,y) {   df <- as.data.frame(cbind(x,y))   colnames(df) = c("v1","v2")   df <- df[with(df,order(v1,v2)),]   adj.mat <- diag(1,dim(df)[1])   (i in 1:dim(df)[1]) {     (j in 1:dim(df)[1]) {       if((df[i,1]-df[j,1]==0)&(abs(df[i,2]-df[j,2])==1) | (df[i,2]-df[j,2]==0)&(abs(df[i,1]-df[j,1])==1)) {         adj.mat[i,j] = 1       }     }   }   return(adj.mat) }  ## here's adjacency matrix adjacency.coordinates(x,y) 

does know of way work on set of coordinates couple thousand pixels long? i've tried conversion spatialgriddataframe , went there won't adjacency matrix correct. thank time.

while thought igraph might way go here, think can more like:

result <- apply(df, 1, function(pt)    (pt["x"] == df$x &  abs(pt["y"] - df$y) == 1) |   (abs(pt["x"] - df$x) == 1 &  pt["y"] == df$y)     ) diag(result) <- 1 

and avoid loopiness , same result:

> identical(adjacency.coordinates(x,y),result) [1] true 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -