Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
61 views7 pages

ch3 2 Subsetting Matrices

The document introduces subsetting matrices in R. It shows how to subset elements, columns, rows, and multiple elements of a matrix using indices. Indexing can be numeric ("m[1,3]") or character ("m["r2","c"]"). Logical vectors can be used to subset elements where the condition is TRUE. Subsetting allows extracting parts of a matrix for further analysis or manipulation.

Uploaded by

Somanshu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views7 pages

ch3 2 Subsetting Matrices

The document introduces subsetting matrices in R. It shows how to subset elements, columns, rows, and multiple elements of a matrix using indices. Indexing can be numeric ("m[1,3]") or character ("m["r2","c"]"). Logical vectors can be used to subset elements where the condition is TRUE. Subsetting allows extracting parts of a matrix for further analysis or manipulation.

Uploaded by

Somanshu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

INTRODUCTION TO R

Subsetting Matrices
Introduction to R

Subset element
> m <- matrix(sample(1:15, 12), nrow = 3)

> m
[,1] [,2] [,3] [,4]
[1,] 5 11 15 3
[2,] 12 14 8 9
[3,] 6 1 4 2

> m[1,3]
[1] 15

> m[3,2]
[1] 1
Introduction to R

Subset column or row > m


[,1] [,2] [,3] [,4]
[1,] 5 11 15 3
> m[3,]
[2,] 12 14 8 9
[1] 6 1 4 2
[3,] 6 1 4 2
> m[,3]
[1] 15 8 4

> m[4]
[1] 11

> m[9]
[1] 4
Introduction to R

Subset multiple elements > m


[,1] [,2] [,3] [,4]
[1,] 5 11 15 3
> m[2, c(2, 3)]
[2,] 12 14 8 9
[1] 14 8
[3,] 6 1 4 2
> m[c(1, 2), c(2, 3)]
[,1] [,2]
[1,] 11 15
[2,] 14 8

> m[c(1, 3), c(1, 3, 4)]


[,1] [,2] [,3]
[1,] 5 15 3
[2,] 6 4 2
Introduction to R

Subset by name
> rownames(m) <- c("r1", "r2", "r3")
> colnames(m) <- c("a", "b", "c", "d")
> m
a b c d
r1 5 11 15 3
r2 12 14 8 9
r3 6 1 4 2

> m[2,3] > m[2,"c"]


[1] 8 [1] 8

> m["r2","c"] > m[3, c("c", "d")]


[1] 8 c d
4 2
Introduction to R

Subset with logical vector > m


a b c d
r1 5 11 15 3
> m[c(FALSE, FALSE, TRUE), 

r2 12 14 8 9
c(FALSE, FALSE, TRUE, TRUE)]
r3 6 1 4 2
c d
4 2

> m[c(FALSE, FALSE, TRUE),


c(FALSE, TRUE)]
b d
1 2

> m[c(FALSE, FALSE, TRUE),


c(FALSE, TRUE, FALSE, TRUE)]
b d
1 2
INTRODUCTION TO R

Let’s practice!

You might also like