问题描述
我有来自横断面的动物调查数据。横断面分为多个部分。有一些部分的起点/终点的纬度/经度数据,但没有其他部分,我想计算缺少这些值的部分的起点/终点。缺失的起点/终点应使用截面方位角(度)、截面长度(米)计算。
示例数据:
部分 | StartLon | 起始纬度 | EndLon | EndLat | 轴承 | 长度 |
---|---|---|---|---|---|---|
1 | -132.4053 | 53.00704 | -132.4053 | 53.00714 | 360 | 5 |
2 | -132.4053 | 53.00714 | 不适用 | 不适用 | 360 | 10 |
我正在尝试使用 destPoint (geosphere) 来计算缺失的起点/终点 (NA)。 destPoint 的输出如下所示:
lon lat
[1,] -132.4053 53.00701
我的代码:
data %>%
mutate(EndLon = if_else(is.na(EndLon),destPoint(c(StartLon,StartLat),bearing,Length),EndLon))
data %>%
mutate(EndLat = if_else(is.na(EndLat),EndLat))
Error: Problem with `mutate()` input `test`.
x Wrong length for a vector,should be 2
i Input `test` is `if_else(...)`
我认为错误是因为destPoint的输出是两个值(lon和lat),而mutated列只能容纳一个值。也许有一种方法可以使用 select() 以便只有 lon 或 lat 进入变异列?
解决方法
我们可能会使用 rowwise
library(dplyr)
library(geosphere)
data %>%
rowwise %>%
mutate(EndLon = if(is.na(EndLon))
destPoint(c(StartLon,StartLat),Bearing,Length)[,'lon'] else EndLon) %>%
ungroup
-输出
# A tibble: 2 x 7
# Section StartLon StartLat EndLon EndLat Bearing Length
# <int> <dbl> <dbl> <dbl> <dbl> <int> <int>
#1 1 -132. 53.0 -132. 53.0 360 5
#2 2 -132. 53.0 -132. NA 360 10
数据
data <- structure(list(Section = 1:2,StartLon = c(-132.4053,-132.4053
),StartLat = c(53.00704,53.00714),EndLon = c(-132.4053,NA
),EndLat = c(53.00714,NA),Bearing = c(360L,360L),Length = c(5L,10L)),class = "data.frame",row.names = c(NA,-2L))
问题在于 c(StartLon,StartLat)
会连接来自这两列的整个列值,因此 length
的参数之一的 if_else
在 {{1 }} 比其他的。如果我们做length
,它被rowwise
分组,我们可以使用row
(这需要if/else
1的输入逻辑表达式)