0

I am trying to analyze avg distance between two locations to come with an acceptable cutoff for auto approval of traveled distance. I have tied referring to (geosphere distHaversine() & dplyr - error wrong length for vector, should be 2) & (Getting Error in .pointsToMatrix(p1) : Wrong length for a vector, should be 2) but I am unable to debug the error and complete my analysis.

Data frame is something like this with 10 rows of data.

df <- c(lat1,long1,lat2,long2)

df matrix with 10 rows of data

when I try to use the following

df %>% rowwise() %>% mutate(HVRSINE = distHaversine(c(df$long1,df$lat1),c(df$long2,df$lat2)))

the error comes as:

Error: Problem with `mutate()` column `HVRSINE`.
x Wrong length for a vector, should be 2

The error occurred in row 1.

when i manually write lat,long for in the disthaversine, the output works like a charm.

What am I doing wrong?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
am_2190
  • 1
  • 1
  • Don't use `$` in `dplyr` commands. `df$long1` overrides `dplyr`'s non-standard evaluation to specifically pull the entire `long1` column from the whole `df`, ignoring the `rowwise` and any `group_by`, and any other fancy `dplyr` stuff. Change to `mutate(HVRSINE = distHaversine(c(long1, lat1), c(long2, lat2)))` and I think it should work. – Gregor Thomas May 25 '21 at 14:31
  • if you want an answer based on your sampledata, please edit your post with the output of (something like) `dput(head(df))`. – Wimpel May 25 '21 at 14:36

1 Answers1

0

try

library(tidyverse)
df %>%
  mutate(HVRSINE = unlist(pmap(list(a = long1, 
                                    b = lat1, 
                                    x = long2,
                                    y = lat2),
                               ~ distHaversine(c(..1, ..2), c(..3, ..4)))))
Wimpel
  • 26,031
  • 1
  • 20
  • 37