'How can I access a matrix entries using a for loop in R?

I have a distance matrix with all distances between a all points in the data set. How can I access the individual distances in the matrix without using a for loop?

This is a working example using a for loop:

# Create a distance matrix of all possible distances
DistMatrix <- Stations %>% 
  st_sf(crs = 4326) %>% 
  filter(!is.na(end.station.id)) %>% 
  st_distance(Stations$geometry)

# initialisation of new distance data frame Dist containing start and end station id. 
Dist <- Bike %>% 
  select(start.station.id, end.station.id, dateS, tripduration) %>% 
  filter(!is.na(end.station.id)) %>%
  mutate(Dist = NA)

# iterates over all rows and allocates the corresponding distance to start and end station id's. 
for(i in 1:length(Dist$dateS)){
  Dist$Dist[i] <- DistMatrix[which(Stations$end.station.id == Dist$end.station.id[i]),
                             which(Stations$end.station.id == Dist$start.station.id[i])]
}

This is my best try go at this problem using dplyr::mutate:


Dist2 <- Dist2 %>% mutate(Dist = DistMatrix[which(end.station.id == Stations[1]),
                                            which(start.station.id == Stations[1])])

The expected outcome would be that the dataframe Dist is edited with the column Dist(distances): enter image description here

Is there a working solution to this problem?

Thx!

EDIT: The example code is more detailed now. EDIT 2: Added expected out come.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source