2012-01-19 65 views
1

儘可能快,我想用存儲在另一個向量中的值替換矩陣某些行中的第一個零。替換矩陣行中的第一個零元素,

有一個數字矩陣,其中每一行是一個有零點的向量。 我也有兩個向量,其中一個包含行,在要替換的內容中,另一個是新值:replace.in.these.rowsnew.values。另外,我可以產生第一個零與sapply矢量

mat <- matrix(1,5,5) 
mat[c(1,8,10,14,16,22,14)] <- 0 
replace.in.these.rows <- c(1,2,3) 
new.values <- c(91,92,93) 

corresponding.poz.of.1st.zero <- sapply(replace.in.these.rows, 
             function(x) which(mat [x,] == 0)[1]) 

現在我想的東西,在索引向量的迭代,但沒有一個for循環可能:

matrix[replace.in.these.rows, corresponding.poz.of.the.1st.zero ] <- new.values 

有一招索引不僅僅是簡單的向量?它不能使用列表或數組(例如逐列)作爲索引。

默認情況下,R矩陣是一組列向量。如果我將數據存儲在轉置表單中,我會獲得任何收益嗎?這將意味着在列而不是行上工作。


上下文

該矩陣存儲接觸的網絡的ID-S。這不是鄰接矩陣n x n,而是n x max.number.of.partners(或n * = 30)矩陣。

默認情況下,網絡使用edgelist,但我想將「從X的所有鏈接」存儲在一起。

我假定,但不知道這是更有效的比總是提取從EdgeList都(多次每一輪在仿真中)的信息

我還假定該直線生長矩陣形式比存儲快相同格式化列表中的相同信息。

對這些背景假設的一些評論也是受歡迎的。

+0

'矩陣[replace.in.these.rows + nrow(矩陣)*(corresponding.poz.of.the.1st.zero-1)] < - new.values' – James

回答

1

編輯:如果只有第一個零都被替換,然後這種方法的工作原理:

first0s <-apply(mat[replace.in.these.rows, ] , 1, function(x) which(x==0)[1]) 
mat[cbind(replace.in.these.rows, first0s)] <- new.values 
> mat 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 91 1 1 0 1 
[2,] 1 1 1 1 92 
[3,] 1 93 1 1 1 
[4,] 1 1 0 1 1 
[5,] 1 0 1 1 1 

編輯:我認爲目標是取代所有零在選擇行,這是這種方法。一個完全矢量化的方法:

idxs <- which(mat==0, arr.ind=TRUE) 
# This returns that rows and columns that identify the zero elements 
# idxs[,"row"] %in% replace.in.these.rows 
# [1] TRUE TRUE FALSE FALSE TRUE TRUE 
# That isolates the ones you want. 
# idxs[ idxs[,"row"] %in% replace.in.these.rows , ] 
# that shows what you will supply as the two column argument to "[" 
#  row col 
#[1,] 1 1 
#[2,] 3 2 
#[3,] 1 4 
#[4,] 2 5 
chosen.ones <- idxs[ idxs[,"row"] %in% replace.in.these.rows , ] 
mat[chosen.ones] <- new.values[chosen.ones[,"row"]] 
# Replace the zeros with the values chosen (and duplicated if necessary) by "row". 
mat 
#---------  
[,1] [,2] [,3] [,4] [,5] 
[1,] 91 1 1 91 1 
[2,] 1 1 1 1 92 
[3,] 1 93 1 1 1 
[4,] 1 1 0 1 1 
[5,] 1 0 1 1 1 
+0

很好的答案和註釋使得邏輯非常容易遵循。 +1 –

+0

...但這會取代所有零值,而不僅僅是每列中的第一個?! – Tommy

+0

對。我認爲那是要求的。如果需要不同的東西,那麼它可以很容易地修改。也許我錯過了一個修改? –

相關問題