From the course: R for Data Science: Lunch Break Lessons

matrix, row, and column

- [Yash] Hi mark, how it's going? - Oh hi, Yash. - [Yash] Hey guess what, I'm going to Europe, and I have a special deal on a car rental. For a low, low price, I can pick up the car in one city and drop it off in another. The only caveat is that I only get 460 kilometers of mileage, but I'm not sure which two cities are 460 kilometers apart. Can you help me? - I just happen to have a list of European cities and the distances from one to the other. How about we use some R code to answer your question. - [Yash] Wow, how convenient. - Let's start by creating a matrix. And here's what that looks like. The row names indicate possible cities to start. The column names indicate a possible ending city. Now I can use R to see if any distances between two cities equals 460 kilometers. Hey look, these six numbers are indexes into the matrix showing the location of distances equal to 460 kilometers. - [Yash] But that doesn't tell me where I should start, only that there are six possible routes. - Yeah, that's a good point. I need to get the row and column names for each 460 kilometers in the matrix. Luckily, R has functions for this called row and col. Row returns a matrix that labels each value in the matrix with the name, or index, of the row as it appears in. Here it is as indexes. So each row is labeled with the row index. That's not particularly useful, so let's add a bit of code to show the city names. I'll add as.factor equals TRUE to show the names. Now I only want the names of the rows that include a value of 460, so I combine the code that shows row names with the code that selects values equal to 460. So those are the names of the cities where you could pick up the car rental. - [Yash] But then what cities are 460 kilometers from those starting cities? Where should I drive to? - The ending cities are in the column names. Use the same code, but substitute col for row. - [Yash] Can I have that information in an organized table, please? - For you, anything. Let me put it into a data frame. - [Yash] Nice, thanks for the hookup, Mark. - You are quite welcome. (laughs)

Contents