8) Combine Vectors to make a Matrix with cbind

This Blog entry is from the Data Structures section in Learn R.

A vector could be viewed as a column in an Excel spreadsheet.  It folows that if there are several vectors,  they would need to be brought together to create a similar structure.  One structure that closely resembles a spreadsheet,  working with the assumption that the contents of that spreadsheet is all the same data type, is a matrix.

To assume that every vector is to be a column in the matrix, the cbind() function is used to bring those columns togeter into this data structure.  

To start,  create three vectors of the same length:

Column1 <- c(1,2,3,4,5,6)
think-of-a-vector-as-a-column-in-r.png

Run the line of script to the console:

create-a-numeric-vector-written-to-r-console.png

Repeat for two new columns,  creating a script block:

Column2 <- c(10,20,30,40,50,60)
Column3 <- c(100,200,300,400,500,600)
two-vectors-of-same-length-in-r-script.png

Run each new line of script to console.  It is important to note that each line of script will have to be run to the console individually by navigating to the end of the line,  clicking the Run button (or CTRL+Enter) and repeating a click of the Run button upon the cursor being moved to the next line.  Hitherto this procedure of running more lines to console will be referred to as running the script block to console.

more-vectors-of-same-length-in-r-script.png

It can be observed that there are now three Vectors,  columns,  in the environment pane:

vectors-of-same-length-in-rstudio-environment.png

The task is to bring these columns together into a Matrix,  rather bind these colums.  The cbind() function is used to instruct this binding of columns.  Type:

Matrix3Col <- cbind(Column1,Column2,Column3)
bringing-vectors-together-using-cbind-in-r.png

Run the line of script to console:

bringing-vectors-together-using-cbind-written-to-r-console.png

It can be seen that a new section in the environment pane has been created, titled Data:

a-matric-created-in-environment-variables-in-r-studio.png

Naturally the new matrix can be viewed by simply typing the Matrix name:

Matrix3Col
a-script-to-write-out-a-matrix-in-r.png

Run the line of script to console:

a-matrix-written-out-to-the-r-console.png