Robbie10538
Robbie10538

Reputation: 1

Converting a vector to input of a matrix/array

Say one has

input=c(1,2)
mat=matrix(1:9,ncol=3)

how does one convert the input vector into a form that allows one to call

mat[input]

and receive the mat[1,2] element of the matrix? I ask because I want to edit elements of an array of length n.

Upvotes: 0

Views: 50

Answers (1)

DanY
DanY

Reputation: 6073

Short Answer:

mat[t(input)]

Explanation:

Chambers' book Software for Data Analysis lists 4 ways to subset (i.e., extract elements of) a matrix. Method #2 is the answer to the question posted above. I'll post each of Chambers' 4 ways with a short example. For the examples, we'll use the matrix m and we'll extract elements in the (4,1) and (6,2) positions, which have values 104 and 116, respectively.

m <- matrix(101:120, ncol=2)

1. Separately index the columns and rows:

m[4,1]
m[6,2]

2. Use a 2-column matrix as a single index argument

k <- rbind(c(4,1), c(6,2))
m[k]

3. Use logical expressions

m[1:10 == 4, 1:2 == 1]
m[1:10 == 6, 1:2 == 2]
#or
m[1:20 %in% c(4,16)]

4. Use vector subsetting because a matrix is just a vector wrapped columnwise

m[c(4,16)]

Here's a screenshot of Chambers' book pages 201--202:

Chambers Book pages 201-202

Upvotes: 2

Related Questions