A primary purpose and use for transposing matrices is to determine if the transposed matrix is equal to the original. If the two matrices are not equal, then the original matrix is asymmetrical. Otherwise, it is symmetrical. That’s the purpose.

Here’s the code. In SQL, tranposing is pretty straightforward. First, let’s get the data for a 3×3 matrix that’s stored in a table in a database:

SELECT * FROM tableA; row_number column_number value 1 1 0 1 2 1 1 3 0 2 1 1 2 2 0 2 3 1 3 1 1 3 2 1 3 3 0

Next, create a view. The view is the transpose. Notice that it’s a matter of switching the order of the columns in the SELECT used to create the view:

CREATE VIEW tableA_transpose (row_number, column_number, value) AS SELECT column_number , row_number , value FROM tableA;

Now, query the view and confirm that it is the transpose:

SELECT * FROM tableA_transpose ORDER BY row_number, column_number; row_number column_number value 1 1 0 1 2 1 1 3 1 2 1 1 2 2 0 2 3 1 3 1 0 3 2 1 3 3 0

Looks good. That’s how to do it in SQL. Here’s the R version.

First, I saved the query results from the original query to a .txt file for use in importing it into R. I saved the file with the column header that I’ll remove while reading. This is a simple trick to overcome problems with unreadable characters that the R `scan()`

function might have trouble reading. Making sure to use UTF-8 character encoding consistently is the best way to avoid read problems later on.

Here’s the R code:

> file.name <- "C:/Users/user/workspace/input_to_r_one_column.txt" > x <- scan(file.name, skip = 1) Read 9 items > x [1] 0 1 0 1 0 1 1 1 0

Typing `y`

at the RStudio console shows that original original matrix was properly created and loaded:

> y <- matrix(x, 3, 3) > y [,1] [,2] [,3] [1,] 0 1 1 [2,] 1 0 1 [3,] 0 1 0

Wait. There’s a problem. The output file saved from the SQL is in row_number, column_number order. R creates column vectors; the values are loaded in column order so the matrix `y`

is the transpose already. This is one of the features of R that I don’t appreciate. If we want to compare the matrices to determine if the original is symmetric or not, we still need the original matrix.

Transposing matrices in R is simple. To transpose matrix `y`

, use the R `t()`

function:

> z <- t(y) > z [,1] [,2] [,3] [1,] 0 1 0 [2,] 1 0 1 [3,] 1 1 0

Reviewing the both the original and transposed matrices, the results obtained from both SQL and R corroborate as we expect. Visual inspection in this simple case does show that the original matrix is asymmetrical.