如何从R中的网格坐标创建邻接矩阵? [英] How to create adjacency matrix from grid coordinates in R?

查看:328
本文介绍了如何从R中的网格坐标创建邻接矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这个网站的新手。我想知道是否有人有过翻转网格坐标列表的经验(在下面的示例代码中以df表示)。我编写了一个函数,可以处理非常小的数据集,但是运行时间会随着数据集大小的增加而呈指数增长(我认为800像素大约需要25个小时)。这是因为嵌套的for循环,但是我不知道如何解决它。

I'm new to this site. I was wondering if anyone had experience with turning a list of grid coordinates (shown in example code below as df). I've written a function that can handle the job for very small data sets but the run time increases exponentially as the size of the data set increases (I think 800 pixels would take about 25 hours). It's because of the nested for loops but I don't know how to get 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 what it looks like as an image
a <- 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 my 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])
  for (i in 1:dim(df)[1]) {
    for (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 the adjacency matrix
adjacency.coordinates(x,y)

有人知道这样做的方法可以在几千像素长的一组坐标上很好地工作吗?我尝试了转换为SpatialGridDataFrame并从那里进行了转换,但无法正确获得邻接矩阵。非常感谢您抽出宝贵的时间。

Does anyone know of a way to do this that will work well on a set of coordinates a couple thousand pixels long? I've tried conversion to SpatialGridDataFrame and went from there but it won't get the adjacency matrix correct. Thank you so much for your time.

推荐答案

虽然我认为 igraph 也许是去这里的方法,我想您可以更简单地做到:

While I thought igraph might be the way to go here, I think you can do it more simply 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 the loopiness and get the same result:

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

这篇关于如何从R中的网格坐标创建邻接矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆