OmZPrime
OmZPrime

Reputation: 25

Removing 0 values from a matrix in R

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

Upvotes: 0

Views: 490

Answers (2)

Santanu
Santanu

Reputation: 382

You can try to calculate the second-smallest value.

apply(mDis,1, function(x)sort(x)[2])

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76402

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

Upvotes: 1

Related Questions