0

So i have a matrix that was generated using the distm() function to generate the distance between stations in a datatable and apply the minimum distance of each station to a new datatable but because it also compares each station with it self it has 0 as the minimum value for each row in the matrix. So i'm looking for a way to get rid of the 0's.

This is what i've used to generate the matrix:

library(geosphere)

mDis = distm( nStnData[,c("Longitude", "Latitude")], nStnData [,c("Longitude", "Latitude")], fun = distVincentyEllipsoid)

This is how i'm trying to apply the minimum distance for each station to the new datatable:

t$minDistance = apply(mDis, 1, min)

This is what it saves: 1

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
OmZPrime
  • 15
  • 5
  • 1
    Welcome to SO! Please take a moment to read about how to post R examples: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – YOLO Jan 11 '20 at 16:43
  • If you want the minimum value that is not zero, why not `mDis2 <- mDis; mDis2[mDis2 == 0] <- Inf`. Then `apply(mDis2, 1, min)`? – Rui Barradas Jan 11 '20 at 16:49

2 Answers2

1

You can set the zero values to Infand take the minimum of the resulting vector. This can be done without creating an extra matrix. Define an anonymous function in the call to apply to do it.

I will use the first example in ?distm since the question does not have a reproducible example that we can copy&paste to an R session.

library(geosphere)

xy <- rbind(c(0,0),c(90,90),c(10,10),c(-120,-45))
mDis <- distm(xy)

apply(mDis, 1, function(x){
  x[x == 0] <- Inf
  min(x)
})
#[1]  1565109  8896111  1565109 12317881
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Dude...you're the BEST. It worked. Tell me how did you learn R. Currently studying data science and need good sources to learn from. – OmZPrime Jan 11 '20 at 17:33
  • @OmZPrime Start with the documentation that comes with R, file `R-intro.pdf`, and check out what CRAN has in its site. – Rui Barradas Jan 11 '20 at 22:44
0

You can try to calculate the second-smallest value.

apply(mDis,1, function(x)sort(x)[2])
Santanu
  • 362
  • 1
  • 6