2014-10-09 98 views
0

我有一個矩陣(expTrans),它當前被零填充。我有第二個矩陣(expCoor),第二列填充列名,第三列填充行號。我想使用第二個矩陣中的座標將第一個矩陣中的某些元素更改爲1。當我使用這個代碼,R填充在具有1中提到的每一列中提到的每行(列出來相同):R:使用單獨的座標矩陣訪問矩陣的元素

expTrans<-matrix(0, nrow(cashflows), ncol(dmat)) 
colnames(expTrans)<-substr(colnames(dmat),4,6) 
expTrans[expCoor[,3],colnames(expenses)[expCoor[,1]]]<-1 

是否有一種方法來改變僅通過各座標所指定的行和列,而不必循環遍歷整個矩陣?

下面是一個簡單的例子來說明什麼我談論:

> m<-matrix(0,ncol=10,nrow=10) 
> colnames(m)<-c("a","b","c","d","e","f","g","h","i","j") 
> m 
     a b c d e f g h i j 
[1,] 0 0 0 0 0 0 0 0 0 0 
[2,] 0 0 0 0 0 0 0 0 0 0 
[3,] 0 0 0 0 0 0 0 0 0 0 
[4,] 0 0 0 0 0 0 0 0 0 0 
[5,] 0 0 0 0 0 0 0 0 0 0 
[6,] 0 0 0 0 0 0 0 0 0 0 
[7,] 0 0 0 0 0 0 0 0 0 0 
[8,] 0 0 0 0 0 0 0 0 0 0 
[9,] 0 0 0 0 0 0 0 0 0 0 
[10,] 0 0 0 0 0 0 0 0 0 0 
> ind<-cbind(sample(1:10,10),sample(1:10,10), c("a","a","b","j","c","d","e", "a", "b", "b")) 
> ind 
     [,1] [,2] [,3] 
[1,] "4" "8" "a" 
[2,] "2" "9" "a" 
[3,] "9" "3" "b" 
[4,] "3" "1" "j" 
[5,] "7" "4" "c" 
[6,] "10" "7" "d" 
[7,] "8" "6" "e" 
[8,] "1" "2" "a" 
[9,] "6" "5" "b" 
[10,] "5" "10" "b" 
> m[as.numeric(ind[,1]),ind[,3]]<-1 
> m 
     a b c d e f g h i j 
[1,] 1 1 1 1 1 0 0 0 0 1 
[2,] 1 1 1 1 1 0 0 0 0 1 
[3,] 1 1 1 1 1 0 0 0 0 1 
[4,] 1 1 1 1 1 0 0 0 0 1 
[5,] 1 1 1 1 1 0 0 0 0 1 
[6,] 1 1 1 1 1 0 0 0 0 1 
[7,] 1 1 1 1 1 0 0 0 0 1 
[8,] 1 1 1 1 1 0 0 0 0 1 
[9,] 1 1 1 1 1 0 0 0 0 1 
[10,] 1 1 1 1 1 0 0 0 0 1 

我預想列有3分1秒(行4,2,8),列b有3分1秒(9行,6列),列c有11(行7),列d有1 1(行10),列e有1 1(行8),列j有1 1(行3)。

+0

你可以提供一個簡單的數據例子嗎?現在你有'expTrans''現金流''dmat''費用'和'expCoor'。所有這些都是代表你的問題的必要條件嗎?我無法弄清楚你 – thelatemail 2014-10-09 23:29:52

+0

另外,你說'expCoor'中的** 2nd **列包含你的列名,那麼爲什麼你在你裏面引用'expCoor [,1]'而不是'expCoor [,2]' r列索引的最後一行代碼是什麼? – thelatemail 2014-10-09 23:32:44

回答

3

有一種方法使用兩列數字矩陣用於「[」或「[< - 」。如果你想要做某種查找的列和rownames的,當且僅當您提供了適當的可重複的例子,可能是可能的(

> expTrans<-matrix(0, 3,4);expTrans 
    [,1] [,2] [,3] [,4] 
[1,] 0 0 0 0 
[2,] 0 0 0 0 
[3,] 0 0 0 0 
> dmat <- matrix(c(1,3,4,2,2,2),ncol=3, byrow=TRUE);dmat 
    [,1] [,2] [,3] 
[1,] 1 3 4 
[2,] 2 2 2 
> colnames(expTrans)<- colnames(dmat); rownames(expTrans) <-rownames(dmat) 
> expTrans[cbind(dmat[,2],dmat[,3])] <- dmat[,1] 
> expTrans 
    [,1] [,2] [,3] [,4] 
[1,] 0 0 0 0 
[2,] 0 2 0 0 
[3,] 0 0 0 1 
> ?'[' 

解決方案經修訂的問題:

> m[cbind(as.numeric(ind[,1]), match(ind[,3], colnames(m))) ] <- 1 
> m 
     a b c d e f g h i j 
[1,] 0 1 0 0 0 0 0 0 0 0 
[2,] 0 1 0 0 0 0 0 0 0 0 
[3,] 0 0 0 1 0 0 0 0 0 0 
[4,] 1 0 0 0 0 0 0 0 0 0 
[5,] 0 0 0 0 0 0 0 0 0 1 
[6,] 0 1 0 0 0 0 0 0 0 0 
[7,] 0 0 0 0 1 0 0 0 0 0 
[8,] 1 0 0 0 0 0 0 0 0 0 
[9,] 0 0 1 0 0 0 0 0 0 0 
[10,] 1 0 0 0 0 0 0 0 0 0 
+0

上面提供的例子,謝謝 – user3390169 2014-10-10 02:52:40

+0

好的。提供解決方案記住...... _numeric_ – 2014-10-10 04:10:09

+0

工作!謝謝! – user3390169 2014-10-10 13:33:26