替换矩阵条目的快捷方式:
# I would like to set values of (1,1) and (2,2) entries of `m` matrix to 3,
# obviously below code
# replaces also values in (1,2) and (2,1) also, is the is way to replace
# entries in proper way without using for()
m <- matrix(0,5,3)
m[1:2,1:2] <- 1
#>m
# [,1] [,2] [,3]
#[1,] 1 1 0
#[2,] 1 1 0
#[3,] 0 0 0
#[4,] 0 0 0
#[5,] 0 0 0
应该可以,因为我们可以将matrix
视为vector
,并在矩阵对象matrix[]
上使用向量记号而不是矩阵表示法matrix[,]
答案 0 :(得分:3)
您可以通过m[matrix(c(1,2,1,2),ncol=2)] <- 1
扩展形式中的相同内容:
m.subset <- matrix(c(1,2,1,2),ncol=2)
# [,1] [,2]
#[1,] 1 1
#[2,] 2 2
m[m.subset] <- 1
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 0
#[4,] 0 0 0
#[5,] 0 0 0