Skip to content
Prev 244213 / 398506 Next

Efficient way to use data frame of indices to initialize matrix

On Dec 7, 2010, at 1:49 PM, Greg Snow wrote:

            
cbind is also useful for assembly of arguments to the  matrix-`[<-`  
function:

tmpdf <- data.frame( x = c(1,2,3), y=c(2,3,1), a=c(10,20,30) )
  mymat <- matrix(NA, ncol=max(tmpdf$y), nrow=max(tmpdf$x))
  mymat[ cbind(tmpdf$x,tmpdf$y) ] <- tmpdf$a

  mymat
      [,1] [,2] [,3]
[1,]   NA   10   NA
[2,]   NA   NA   20
[3,]   30   NA   NA
David Winsemius, MD
West Hartford, CT