Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

r - Mutate when function output has data in two columns (geosphere)

I have animal survey data from transects. Transects are divided into sections. There are lat/lon data for the start/endpoints of some sections but not others, and I want to calculate the start/endpoints for sections where these values are missing. Missing start/endpoints should be calculated using the section bearing (degrees), section length (m).

Example data:

Section StartLon StartLat EndLon EndLat Bearing Length
1 -132.4053 53.00704 -132.4053 53.00714 360 5
2 -132.4053 53.00714 NA NA 360 10
question from:https://stackoverflow.com/questions/65908504/mutate-when-function-output-has-data-in-two-columns-geosphere

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We may use rowwise

library(dplyr)
library(geosphere)
data %>%
    rowwise %>%
    mutate(EndLon = if(is.na(EndLon)) 
       destPoint(c(StartLon, StartLat), Bearing, Length)[, 'lon'] else EndLon) %>%
    ungroup

-output

# 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

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))

The issue would be that c(StartLon, StartLat) would concatenate the whole column values from both of those column, and thereby the length of one of the arguments for if_else becomes different in length than the rest. If we do the rowwise, it is grouped by row and we can use if/else (which requires a input logical expression of length 1)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...