r - 通过坐标将行和列分配给数据框中的点
问题描述
具有 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
解决方案
使用库(光栅)
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
推荐阅读
- java - sql(postgres)-如何创建一个触发器,将表中的两行相乘并将它们添加到另一个表中的一行?
- netcdf - xarray DataArray.where() 掩蔽时减少坐标
- android - 始终收到错误“模拟器:ANSICON:cmd.exe:不受支持的进程。” 在 Android Studio 中
- ruby-on-rails - Shopify Polaris 页面标签不起作用 - Rails 和 reactJS
- c# - 将一些字符串连接到 C# 中的全局变量中
- javascript - 获取不同的两个数组到变量
- android - 是否可以显式检查 onRequestPermissionsResult 中的权限?
- java - Android 在后台运行一段时间后杀死了我的应用
- ruby-on-rails-5 - 在 Rails 5.2 上使用两种不同用户模型的 Bcrypt
- scala - Scala Option[String] map 变成 Iterable