Stat133Lecture3

Stat133Lecture3 - Announcement There will be another Short...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Announcement: There will be another “Short Assignment” posted later today and due Monday night. Today’s topics Data structures galore: matrices, arrays, data frames, and lists More ways to operate efficiently on entire data structures and avoid looping 1 Thursday, September 4, 2008
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
You can create a matrix in R using the matrix function. By default, matrices in R are assigned by column-major order. You can assign them by row-major order by setting the byrow argument to TRUE. Note that the first argument to matrix is a vector, so all elements must be of the same type (numeric, character, or logical). > m <- matrix(1:6, nrow = 2, ncol = 3) > m [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 > m <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE) > m [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 2 Thursday, September 4, 2008
Background image of page 2
Assign names to the rows and columns of a matrix: > rownames(m) <- letters[1:2] > colnames(m) <- letters[1:3] > m a b c a 1 2 3 b 4 5 6 Find the dimensions of a matrix: > dim(m); nrow(m); ncol(m) [1] 2 3 [1] 2 [1] 3 Exchange rows and columns: > t(m) # t for transpose a b a 1 4 b 2 5 c 3 6 3 Thursday, September 4, 2008
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
To index elements of a matrix, use the same five methods of indexing we covered for vectors, but with the first index for rows and the second for columns. Note: by default the result is coerced to a vector if possible, rather than a matrix with a single row or column. Can you guess what each line returns? > m a b c a 1 3 5 b 2 4 6 > m[-1, 2] > m["a",] # By name, empty column index > m[, c(TRUE, TRUE, FALSE)] # Empty row index, logical 4 Thursday, September 4, 2008
Background image of page 4
To avoid the coercion to lower dimension, add the argument drop = FALSE to the indexing. > m[1, 1, drop = FALSE] a a 1 > m[1, , drop = FALSE] # Note empty column index! a b c
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/08/2010 for the course STAT 133 taught by Professor Staff during the Spring '08 term at Berkeley.

Page1 / 17

Stat133Lecture3 - Announcement There will be another Short...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online