Dear R-user community, I need to solve a problem related to river management. The task is to calculate the distance from specified points in a river to the outlet of the river. The river is defined by a database (here called "M"): LinkID |NodeID1 | NodeID2 |Distout |Length ---------------------------------------------------------------------------- 10 |100 |200 |10 | 80 80 |200 |180 |30 | 40 15 |180 |400 |50 | 10 50 |400 |170 |80 | 5 . Where LinkID is a unique ID for a given segment of the river, NodeID1 & NodeID2 define IDs for the start- and endpoint of the given river segment (the water always runs from NodeID1 to NodeID2) respectively, Distout and Length define the distance to the outlet and the length of the river segment respectively. As you can see from the database "M", the value of NodeID1 in a river segment equals the value of NodeID2 of the upstream river segment. It's a huge matrix, so I only show you the concept of it here. So, how to solve the problem? This was my idea: 1) Define the initial value of NodeID2 (e.g. NodeID == 170) and get the values of LinkID, NodeID1, Distout and Length of this row. This defines the river segment at the river outlet. 2) Get the values of the subsequent upstream river segment from knowledge of the value of NodeID2 of the downstream river segment (here initial) 3) Continue as in 2). In a programming concept this would be something like: //Initial condition: R1 = M[NodeID2 == 170,] // Subsequent calculations: R2 = M[NodeID2 == R1[,2],] R3 = M[NodeID2 == R2[,2],] R4 = M[NodeID2 == R3[,2],] Where R refer to result nr. 1,2, .. In "R-language" I tried the following script, but did not succeed: For (i in 1:4){ if (i == 1) R[i] = M[NodeID2 == 170,] else R[i] = M[NodeID2 == R[i-1][,2],] } Can someone help solving the task? Thanks in advance! All the best, Johan [[alternative HTML version deleted]]