# [R] create a function with "subset" statement

Kathryn Lord kathryn.lord2000 at gmail.com
Wed Jan 28 20:54:33 CET 2015

```Dear R experts,

Suppose I have a matrix A below.

a <- rep(1:4, each=5)
b <- rep(1:5, 4)
c <- rnorm(20)

A <- cbind(a,b,c)

> A
a b            c
[1,] 1 1  0.761806718
[2,] 1 2  0.239734573
[3,] 1 3 -0.728339238
[4,] 1 4 -0.121946174
[5,] 1 5 -0.131909077
[6,] 2 1 -0.069790098
[7,] 2 2  1.082671767
[8,] 2 3 -0.869537195
[9,] 2 4 -0.417222758
[10,] 2 5 -2.432273481
[11,] 3 1  0.425432121
[12,] 3 2 -2.453299938
[13,] 3 3  0.612125174
[14,] 3 4 -0.005387462
[15,] 3 5  1.911146222
[16,] 4 1  0.161408685
[17,] 4 2  0.567118882
[18,] 4 3 -0.948882839
[19,] 4 4  0.485002340
[20,] 4 5 -0.551981333

With this matrix A, I'd like to create several sub-matrices, for example

B <- subset(A, (A[,1] %in% c(1,2) & A[,2] %in% c(1,2)) |
(A[,1] %in% c(3)    & A[,2] %in% c(1)  )  |
(A[,1] %in% c(4)    & A[,2] %in% c(1:4)) )

> B
a b          c
[1,] 1 1  0.7618067
[2,] 1 2  0.2397346
[3,] 2 1 -0.0697901
[4,] 2 2  1.0826718
[5,] 3 1  0.4254321
[6,] 4 1  0.1614087
[7,] 4 2  0.5671189
[8,] 4 3 -0.9488828
[9,] 4 4  0.4850023

or

C <- subset(A, (A[,1] %in% c(1:4) & A[,2] %in% c(1,2)) )

> C
a b          c
[1,] 1 1  0.7618067
[2,] 1 2  0.2397346
[3,] 2 1 -0.0697901
[4,] 2 2  1.0826718
[5,] 3 1  0.4254321
[6,] 3 2 -2.4532999
[7,] 4 1  0.1614087
[8,] 4 2  0.5671189

or

D <- subset(A, (A[,1] %in% c(1,2) & A[,2] %in% c(1:3)) |
(A[,1] %in% c(3)    & A[,2] %in% c(1,2)) )

> D
a b          c
[1,] 1 1  0.7618067
[2,] 1 2  0.2397346
[3,] 1 3 -0.7283392
[4,] 2 1 -0.0697901
[5,] 2 2  1.0826718
[6,] 2 3 -0.8695372
[7,] 3 1  0.4254321
[8,] 3 2 -2.4532999

and so forth.

I am wondering if I could create matrices B, C, D etc AT ONE TIME. In order
to do that, I guess I need to make a "function". unfortunately, I have no
idea how to do that.

Any suggestion will be greatly appreciated.

Kathryn Lord

[[alternative HTML version deleted]]

```