[R] Efficient way to use data frame of indices to initialize matrix

David Winsemius dwinsemius at comcast.net
Tue Dec 7 19:59:51 CET 2010


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

> tmpdf <- data.frame( x = c(1,2,3), y=c(2,3,1), a=c(10,20,30) )
> mymat <- matrix(0, ncol=3, nrow=3)
> mymat[ as.matrix(tmpdf[,c('x','y')]) ] <- tmpdf$a

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


> -- 
> Gregory (Greg) L. Snow Ph.D.
> Statistical Data Center
> Intermountain Healthcare
> greg.snow at imail.org
> 801.408.8111
>
>
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
>> project.org] On Behalf Of Cutler, Gene
>> Sent: Tuesday, December 07, 2010 11:31 AM
>> To: r-help at r-project.org
>> Subject: [R] Efficient way to use data frame of indices to initialize
>> matrix
>>
>> I have a data frame with three columns, x, y, and a.  I want to  
>> create
>> a matrix from these values such that for matrix m:
>> m[x,y] == a
>>
>> Obviously, I can go row by row through the data frame and insert the
>> value a at the correct x,y location in the matrix.  I can make that
>> slightly more efficient (perhaps), by doing something like this:
>>> for (each.x in unique(df$x)) m[each.x, df$y[df$x == each.x]] <-
>> df$a[df$x == each.x]
>>
>> But I feel that there must be a more efficient, or at least more
>> elegant way to do this.
>>
>> --
>> Gene
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-
>> guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list