假设我想更改以下矩阵:
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)
。
我可以用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
答案 0 :(得分: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
顺便说一句,这是?"["
:
第三种形式的索引是通过带有一个的数字矩阵 每个维度的列:然后是索引矩阵的每一行 选择数组的单个元素,结果是向量。