Use functions row
and col
together with logical operations. The following works because R's matrices are in column-first order.
mat <- matrix(seq.int(5*4), nrow = 5)
mat[ !(row(mat) %in% 2:4) | !(col(mat) %in% 2:3) ] <- 0
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 0
#[2,] 0 7 12 0
#[3,] 0 8 13 0
#[4,] 0 9 14 0
#[5,] 0 0 0 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…