[英]R: Accessing elements of a matrix using a separate coordinate matrix
我有一個矩陣(expTrans),當前填充了零。 我有第二個矩陣(expCoor),其中第二列用列名填充,第三列用行號填充。 我想使用第二個矩陣中的坐標將第一個矩陣中的某些元素更改為1。 當我使用此代碼時,R用1填充提到的每一列中提到的每一行(各列完全相同):
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
我期望a列具有3 1s(第4,2,8行),b列具有3 1s(9,6,5行),c列具有1 1(第7行),d列具有1 1(第10行),第e列為1 1(第8行),第j列為1 1(第3行)。
有一種方法可以對“ [”或“ [<-”使用兩列數字矩陣。 如果您想對列名和行名進行某種形式的查找,則可能(僅當您提供了適當的可重現示例時)。
> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.