1

假设我想更改以下矩阵:

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

但我想要:

    [,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

将向量视为值的位置 - 将 x,y (4,1) 和 x,y (2,5) c(200,500)分别更改为 in。

我可以用 for 循环做到这一点,但它太慢了。

 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
4

1 回答 1

1
## 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

顺便说一句,这记录在?"["

第三种索引形式是通过一个数字矩阵,每个维度有一列:索引矩阵的每一行然后选择数组的单个元素,结果是一个向量。

于 2013-11-05T08:05:25.147 回答