2015-02-17 49 views
2

快速方式爲矩陣條目的替代:矩陣的選擇的條目的快速置換中的R

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

+1

'm [c(1,7)] < - 1'? – NicE 2015-02-17 23:06:27

回答

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