Home > front end >  How to extract close-by locations from a matrix?
How to extract close-by locations from a matrix?

Time:05-29

I got a matrix containing distances in kilometers in R:

structure(c(0, 0.299178017189202, 0.472092562775104, 31.0627244156583, 
68.5367247200762, 138.470931004348, 0.299178017189202, 0, 0.298855070662631, 
31.1130225293117, 68.70216465045, 138.511349341572, 0.472092562775104, 
0.298855070662631, 0, 31.41104035093, 68.9840966568129, 138.808325566886, 
31.0627244156583, 31.1130225293117, 31.41104035093, 0, 42.1218726943979, 
107.425908015876, 68.5367247200762, 68.70216465045, 68.9840966568129, 
42.1218726943979, 0, 82.3261005757895, 138.470931004348, 138.511349341572, 
138.808325566886, 107.425908015876, 82.3261005757895, 0), .Dim = c(6L, 
6L), .Dimnames = list(c("260100023-01", "260100023-05", "260100034-01", 
"260100034-02", "260100238-00", "260201036-00"), c("260100023-01", 
"260100023-05", "260100034-01", "260100034-02", "260100238-00", 
"260201036-00")))

The ID's are representing different locations. Now, I want to create a list, that shows for every ID, which other ID's are within a radius of 40 kilometers. I suppose the key to do this, is an "if"-function. But I don't know how to apply it line by line on every cell of a matrix.

CodePudding user response:

You can extract the elements from a single column, where the distance is at most 40 as follows:

col <- data[1, ]
col[col < 40]
## 260100023-01 260100023-05 260100034-01 260100034-02 
##   0.0000000    0.2991780    0.4720926   31.0627244 

As you can see, the resulting vector has names which are exactly the IDs of the locations that are within 40 kilometers. Using names(), we can extract the IDs:

names(col[col < 40])
## [1] "260100023-01" "260100023-05" "260100034-01" "260100034-02"

Now that we know how to do this for a single column, we can use apply() to run this function for all columns

apply(data, 2, function(col) names(col[col > 40]))
## $`260100023-01`
## [1] "260100238-00" "260201036-00"
## 
## $`260100023-05`
## [1] "260100238-00" "260201036-00"
## 
## $`260100034-01`
## [1] "260100238-00" "260201036-00"
## 
## $`260100034-02`
## [1] "260100238-00" "260201036-00"
## 
## $`260100238-00`
## [1] "260100023-01" "260100023-05" "260100034-01" "260100034-02" "260201036-00"
## 
## $`260201036-00`
## [1] "260100023-01" "260100023-05" "260100034-01" "260100034-02" "260100238-00"
  • Related