# In R, we assign values to a variable with the "gets" operator ( <- ). # For example, here, we create a variable called x which contains the # values 1, 0, and 1 (collected together with the "c" function). > x <- c(1,0,1) # If we want to see what x contains, we simply type its name: > x [1] 1 0 1 # Here's an easy way to create a matrix in R. First, set a variable # equal to the desired content of each column in the matrix. I'm # going to create a matrix with 3 rows and 4 columns, so I'll need # four variables, which I'll call x1, x2, x3 and x4. I want x1 to # have the values I've already given x, so I'll just make that # assignment directly: > x1 <- x # Next, I assign values to x2, x3, and x4: > x2 <- c(2,2,1) > x3 <- c(4,3,2) > x4 <- c(1,1,5) # Just to confirm, here's the contents of each variable: > x1 [1] 1 0 1 > x2 [1] 2 2 1 > x3 [1] 4 3 2 > x4 [1] 1 1 5 # Now I'm going to create a matrix which I'll call x. (This will overwrite # my previous assignment of the variable x.) I create the matrix by "binding" # together the columns I've created using the "cbind" function: > x <- cbind(x1,x2,x3,x4) # The variable x now contains the desired matrix: > x x1 x2 x3 x4 [1,] 1 2 4 1 [2,] 0 2 3 1 [3,] 1 1 2 5 # Let's create a new matrix variable that we'll arbitrarily call y: > y1 <- c(1,2,5,1) > y2 <- c(2,3,6,1) > y3 <- c(3,4,5,1) > y <- cbind(y1,y2,y3) > y y1 y2 y3 [1,] 1 2 3 [2,] 2 3 4 [3,] 5 6 5 [4,] 1 1 1 > # The matrix multiplication operator in R is %*% . So to multiply the # two matrices we've created, we do this: > x %*% y y1 y2 y3 [1,] 26 33 32 [2,] 20 25 24 [3,] 18 22 22 # I might be that we want to DO something with the results of that # matrix multiplication, rather than just look at it. If so, we'll # want to store it as a variable. I can name it anything without # special characters or spaces; here, I've chosen "result" to remind # myself that it's the RESULT of the matrix multiplication: > result <- x%*%y > > result y1 y2 y3 [1,] 26 33 32 [2,] 20 25 24 [3,] 18 22 22 # A student asked what R would do if we ask it to perform multiplication # on matrices that don't conform. Here, we create an example of such # matrices and attempt the multiplication: > x1 <- c(1,2,2,1,2) > x2 <- c(1,3,1,3,2) > x3 <- c(0,1,1,0,1) > x <- cbind(x1,x2,x3) > x x1 x2 x3 [1,] 1 1 0 [2,] 2 3 1 [3,] 2 1 1 [4,] 1 3 0 [5,] 2 2 1 > y <- c(1,1,2,1,2) > > x %*% y Error in x %*% y : non-conformable arguments # R is unable to perform the operation, and tells us why. > # We can transpose a matrix using the t() function: > x x1 x2 x3 [1,] 1 1 0 [2,] 2 3 1 [3,] 2 1 1 [4,] 1 3 0 [5,] 2 2 1 > t(x) [,1] [,2] [,3] [,4] [,5] x1 1 2 2 1 2 x2 1 3 1 3 2 x3 0 1 1 0 1 > # And we can store the result if we want to. Here, I've chosen the # name tx to remind myself that this is the transpose of x. Note that # tx is a variable name, while t(x) applies the transpose function to # the variable x. > tx <- t(x) > tx [,1] [,2] [,3] [,4] [,5] x1 1 2 2 1 2 x2 1 3 1 3 2 x3 0 1 1 0 1