Create a small matrix of numbers to do some examples

look<- matrix( 1:12, ncol=4, nrow=3)
look
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12

Matrix transpose and dimension

dim( look)
## [1] 3 4
t( look)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
## [4,]   10   11   12

Using cbind to create the matrix column by column

look<- cbind( c( 1:3), c(4:6), c(7:9), c(10:12))

Convert this matrix to a data frame

look2<- data.frame( look)

A data frame can have columns of text (aka strings) sometimes very useful. A matrix can not! In this example the whole matrix is converted to text when this is tried.

look3<- cbind( animals= c("cat", "dog", "lion"), oldData= look2)
print( look3)
##   animals oldData.X1 oldData.X2 oldData.X3 oldData.X4
## 1     cat          1          4          7         10
## 2     dog          2          5          8         11
## 3    lion          3          6          9         12
 cbind( c("cat", "dog", "lion"), look)
##      [,1]   [,2] [,3] [,4] [,5]
## [1,] "cat"  "1"  "4"  "7"  "10"
## [2,] "dog"  "2"  "5"  "8"  "11"
## [3,] "lion" "3"  "6"  "9"  "12"

The column names have been added to make this print more clearly.

Create an NA

look[2,3] <- NA
look
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5   NA   11
## [3,]    3    6    9   12
look2<- is.na( look)
look2
##       [,1]  [,2]  [,3]  [,4]
## [1,] FALSE FALSE FALSE FALSE
## [2,] FALSE FALSE  TRUE FALSE
## [3,] FALSE FALSE FALSE FALSE
 look==4 
##       [,1]  [,2]  [,3]  [,4]
## [1,] FALSE  TRUE FALSE FALSE
## [2,] FALSE FALSE    NA FALSE
## [3,] FALSE FALSE FALSE FALSE

Applying over rows and columns

apply( look, 1, "max")
## [1] 10 NA 12
apply( look, 2, "max")
## [1]  3  6 NA 12

Here is an image plot of this matrix

image(1:3, 1:4, look, col=rainbow(256))

Here is an image plot of this matrix using the fields function that adds a legend

library(fields)
## Loading required package: spam
## Loading required package: grid
## Spam version 1.4-0 (2016-08-29) is loaded.
## Type 'help( Spam)' or 'demo( spam)' for a short introduction
## and overview of this package.
## Help for individual functions is also obtained by adding the
## suffix '.spam' to the function name, e.g. 'help( chol.spam)'.
##
## Attaching package: 'spam'
## The following objects are masked from 'package:base':
##
##     backsolve, forwardsolve
## Loading required package: maps
image.plot(1:3, 1:4, look, col=rainbow(256))