首页 > 解决方案 > 通过坐标将行和列分配给数据框中的点

问题描述

具有 x 和 y 坐标的点列表形成一个方格,我如何知道每个点对应于每个格的哪一行和哪一列?

举一个简单的例子,我将从这样的数据框开始。

x_coordinates <- c(1,2,3,1,2,3)
y_coordinates <- c(1,1,1,2,2,2)
df_points <- data.frame(x_coordinates, y_coordinates)
df_points$row <- NA
df_points$column <- NA
df_points

x_coordinates y_coordinates column row
1             1             1  NA     NA
2             2             1  NA     NA
3             3             1  NA     NA
4             1             2  NA     NA
5             2             2  NA     NA
6             3             2  NA     NA

行和列的位置仍然未知。这个例子的明显答案是:

df_points$column <- c(1,2,3,1,2,3)
df_points$row <- c(1,1,1,2,2,2)
df_points

x_coordinates y_coordinates column row
1             1             1   1      1
2             2             1   2      1
3             3             1   3      1
4             1             2   1      2
5             2             2   2      2
6             3             2   3      2

但我需要将其应用于更大、更复杂的示例,例如:

df_points$x_coordinates <- c(10,30,50,10,30,50)
df_points$y_coordinates <- c(15,15,15,20,20,20)
df_points
              x_coordinates y_coordinates column row
1             10             15           1      1
2             30             15           2      1
3             50             15           3      1
4             10             20           1      2
5             30             20           2      2
6             50             20           3      2

甚至还有行和列未对齐的示例:

  x_coordinates y_coordinates column   row
1             10             15   1      1
2             30             16   2      1
3             50             17   3      1
4             12             20   1      2
5             32             21   2      2
6             52             22   3      2

标签: r

解决方案


使用库(光栅)

find_rowcol = function(df, nrow=2) {
  df[,2] = -df[,2]
  e <- extent(as.matrix(df[,1:2]))
  r <- raster(e, ncol=NROW(df)/nrow, nrow=nrow)
  rowColFromCell(r, cellFromXY(r, df[,1:2]))
}

df_points$x_coordinates <- c(10,30,50,12,32,52)
df_points$y_coordinates <- c(15,16,17,20,21,22)
find_rowcol(df_points)
#      row col
# [1,]   1   1
# [2,]   1   2
# [3,]   1   3
# [4,]   2   1
# [5,]   2   2
# [6,]   2   3

推荐阅读