在 R 中创建 SpatialPointsDataFrame 时如何保留丢失的坐标
How to keep missing coordinates when creating a SpatialPointsDataFrame in R
我有一个动物位置数据集(GPS 位置、纬度和经度),位置之间缺少一些坐标。我正在使用 R 读取它们并更改它们的投影,但我想保留这个缺失的坐标点,以便以后可以对它们进行插值(或可以完成任何其他操作)。
但是,当我尝试将数据转换为 SpatialPointsDataFrame
(稍后使用 spTransform
重新投影)时,出现错误:
Error in .local(obj, ...) : NA values in coordinates
在创建 SpatialPointsDataFrame
时,是否有办法将此 NA 保持在同一个位置?
这里有一些可重现的代码:
mov.data <- data.frame(x = c(-49.8427, -49.85003, NA, -49.84685),
y = c(-21.30366, -21.29498, NA, -21.2944),
time = 1:4, ID = 1)
mov.spdata <- SpatialPointsDataFrame(coords = mov.data[,1:2],
data = mov.data[,3:4])
当我 运行 它时,我得到上面显示的错误。有什么提示吗?
否,sp
对象不允许坐标中存在缺失值。
sp
对象不允许在坐标中缺少值。 discussed on GitHub by Edzer Pebesma,他也在 Whosebug 上(简要地)回答了这个问题。
解决方案:
mov.data <- data.frame(x = c(-49.8427, -49.85003, NA, -49.84685),
y = c(-21.30366, -21.29498, NA, -21.2944),
time = 1:4, ID = 1)
# If there are NA values, replace them by 0 and add a column to keep information
mov.data$is_na = ifelse(is.na(mov.data$x), TRUE, FALSE)
index = mov.data$is_na == TRUE
mov.data[index, "x"] <- 0
mov.data[index, "y"] <- 0
mov.data <- SpatialPointsDataFrame(coords = mov.data[, 1:2],
data = mov.data[, 3:5])
你得到:
coordinates time ID is_na
1 (-49.8427, -21.30366) 1 1 FALSE
2 (-49.85003, -21.29498) 2 1 FALSE
3 (0, 0) 3 1 TRUE
4 (-49.84685, -21.2944) 4 1 FALSE
然后,根据这些信息,您可以进行所有您想要的转换,例如将结果写入 CSV 文件或您想要的任何格式。
我有一个动物位置数据集(GPS 位置、纬度和经度),位置之间缺少一些坐标。我正在使用 R 读取它们并更改它们的投影,但我想保留这个缺失的坐标点,以便以后可以对它们进行插值(或可以完成任何其他操作)。
但是,当我尝试将数据转换为 SpatialPointsDataFrame
(稍后使用 spTransform
重新投影)时,出现错误:
Error in .local(obj, ...) : NA values in coordinates
在创建 SpatialPointsDataFrame
时,是否有办法将此 NA 保持在同一个位置?
这里有一些可重现的代码:
mov.data <- data.frame(x = c(-49.8427, -49.85003, NA, -49.84685),
y = c(-21.30366, -21.29498, NA, -21.2944),
time = 1:4, ID = 1)
mov.spdata <- SpatialPointsDataFrame(coords = mov.data[,1:2],
data = mov.data[,3:4])
当我 运行 它时,我得到上面显示的错误。有什么提示吗?
否,sp
对象不允许坐标中存在缺失值。
sp
对象不允许在坐标中缺少值。 discussed on GitHub by Edzer Pebesma,他也在 Whosebug 上(简要地)回答了这个问题。
解决方案:
mov.data <- data.frame(x = c(-49.8427, -49.85003, NA, -49.84685),
y = c(-21.30366, -21.29498, NA, -21.2944),
time = 1:4, ID = 1)
# If there are NA values, replace them by 0 and add a column to keep information
mov.data$is_na = ifelse(is.na(mov.data$x), TRUE, FALSE)
index = mov.data$is_na == TRUE
mov.data[index, "x"] <- 0
mov.data[index, "y"] <- 0
mov.data <- SpatialPointsDataFrame(coords = mov.data[, 1:2],
data = mov.data[, 3:5])
你得到:
coordinates time ID is_na
1 (-49.8427, -21.30366) 1 1 FALSE
2 (-49.85003, -21.29498) 2 1 FALSE
3 (0, 0) 3 1 TRUE
4 (-49.84685, -21.2944) 4 1 FALSE
然后,根据这些信息,您可以进行所有您想要的转换,例如将结果写入 CSV 文件或您想要的任何格式。