Stat133Lecture3

# Stat133Lecture3 - Announcement There will be another Short...

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

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 efﬁciently on entire data structures and avoid looping 1 Thursday, September 4, 2008

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

View Full Document
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 ﬁrst 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
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

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

View Full Document
To index elements of a matrix, use the same ﬁve methods of indexing we covered for vectors, but with the ﬁrst 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
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

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

View Full Document
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
Ask a homework question - tutors are online