user1436187
user1436187

Reputation: 3376

Changing single data in matrix with vector

Suppose I want to change the following matrix:

a= matrix(c(
  1:20),ncol=5)
a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

rvec= c(4,2)
cvec=c(1,5)
a[rvec,cvec] = c(200,500)
a
    [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]  500    6   10   14  500
[3,]    3    7   11   15   19
[4,]  200    8   12   16  200

but I want:

    [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14  500
[3,]    3    7   11   15   19
[4,]  200    8   12   16  20

Considering the vector as a position of values - changing x,y (4,1) and x,y (2,5) to in c(200,500) respectively.

I can do that with for loops but it is too slow.

 for(i in 1:length(c(200,500)))
 {
   a[rvec[i],cvec[i]] = c(200,500)[i]
 }

 a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14  500
[3,]    3    7   11   15   19
[4,]  200    8   12   16   20

Upvotes: 1

Views: 55

Answers (1)

Josh O'Brien
Josh O'Brien

Reputation: 162321

## Set up a matrix with row-indices in column 1 & column-indices in column 2 
ij <- rbind(c(4,1), c(2,5))

## Use it to pick out individual elements of a
a[ij] <- c(200, 500)

## Check that it worked
a
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    5    9   13   17
# [2,]    2    6   10   14  500
# [3,]    3    7   11   15   19
# [4,]  200    8   12   16   20

This is, by the way, documented in ?"[":

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

Upvotes: 1

Related Questions