R:使用单独的坐标矩阵访问矩阵的元素

时间:2014-10-09 23:22:36

标签: r 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个1(行4,2,8),列b有3个1(行9,6,5),列c有1个1(行7),列d有1 1(第10行),列e具有1 1(第8行),列j具有1 1(第3行)。

1 个答案:

答案 0 :(得分:3)

有一种方法可以使用双列数字矩阵“[”或“[&lt; - ”]。如果你想对列和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