0

I have 3 data sets: one of people, one of stores, and one of farmers markets, each with lat/long points.

PeopleEx <- data.frame(replicate(2,sample(0:10,10,rep=TRUE))) %>%
  rename(lat = X1, long = X2) %>%
  mutate(ID = 1:10, type = "people")

StoresEx <- data.frame(replicate(2,sample(0:10,5,rep=TRUE))) %>%
  rename(lat = X1, long = X2) %>%
  mutate(ID = 1:5, type = "store")

MarketsEx <- data.frame(replicate(2,sample(0:10,1,rep=TRUE))) %>%
  rename(lat = X1, long = X2) %>%
  mutate(ID = 1, type = "market")

Each have a column for "Lat","Long","ID","type", where type can be "people", "market, or "store". I am trying to find the distance between each person and the closest store as well as the closest market. To do so I made a data frame with all 3 data sets.

DfExample <- rbind(PeopleEx, StoresEx, MarketsEx)

I've been using the sp and rgeos packages to calculate distance between points.

sp.DfExample <- DfExample
coordinates(sp.DfExample) <- ~long+lat

The first 10 entries are the people with the last 6 being stores/markets so I've used this code:

Distances <- gDistance(sp.DfExample, byid=T)
DistanceStore <- Distances[1:16, 10:16]
MaxDist <- DistanceStore
apply(MaxDist, 1, FUN=min)

This works in that it reports the minimum distance from each person to a store/market, however it drops the type. Any ideas on how to keep the type from dropping or different packages/approaches to use instead?

  • Welcome to SO. Could you please make your question reproducible: include a minimal dataset in the form of an object for example if a data frame as df <- data.frame(…) where … is your variables and values or use dput(head(df)). Include the code you have tried and set out your expected answer. These links should be of help: [mre] and [ask] – Peter May 21 '20 at 17:47
  • Hi thanks for the patience, I'm still learning how to make proper posts. I edited it a bit so hopefully it is more clear. – Lauren Miller May 21 '20 at 23:26
  • Might this link help? https://stackoverflow.com/questions/32363998/function-to-calculate-geospatial-distance-between-two-points-lat-long-using-r. Naively you could use `data.frame(min_dist_to_store = apply(MaxDist, 1, FUN=min), type = sp.DfExample$type)` – Peter May 22 '20 at 07:52
  • I've checked out that post and the linked ones but they all were just a bitt off of what I was trying to do, with keeping the type attribute and the closest store and market. The sp.DfExample$type is an S4 object of class SpatialPointsDataFrame and I cannot figure out how to make it not drop the type, so the equation above returns an error. – Lauren Miller May 22 '20 at 18:28

0 Answers0