useful math
%% is modulo division (i.e., we just keep track of the remainder)
> 1:9 %% 2 # after dividing by 2, what is left?
[1] 1 0 1 0 1 0 1 0 1
> 1:9 %% 3 # after dividing by 3, what is left?
[1] 1 2 0 1 2 0 1 2 0
> 1:9 %% 4
[1] 1 2 3 0 1 2 3 0 1
%/% is integer division (i.e., we just ignore the remainder)
> 1:9 %/% 2
[1] 0 1 1 2 2 3 3 4 4 # how many times can 2 go into each number?
> 1:9 %/% 3
[1] 0 0 1 1 1 2 2 2 3
> 1:9 %/% 4
[1] 0 0 0 1 1 1 1 2 2
Use matrix(data, nrow, ncol, byrow) to create plot-able, transformable matrices. data is the values in the matrix. nrow is the number of rows, and ncol the number of columns. byrow specifies how to fill the matrix (=TRUE for by row, =FALSE for by column). byrow defaults to FALSE.
Examples (from http://www.ats.ucla.edu/stat/R/library/matrix_alg.htm):
>seq1 <- seq(1:6)
>mat1 <- matrix(seq1, 2)
>mat1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
#filling the matrix by rows
>mat2 <- matrix(seq1, 2, byrow = T)
>mat2
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
>mat3 <- matrix(seq1, ncol = 2)
>mat3
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
#creating the same matrix using both dimension arguments
#by using them in order we do not have to name them
>mat4 <- matrix(seq1, 3, 2)
>mat4
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
See http://www.statmethods.net/advstats/matrix.html for a list of matrix functions.
page revision: 1, last edited: 28 Sep 2009 18:02