[R] Data frame with 3 columns to matrix

David Winsemius dwinsemius at comcast.net
Tue Apr 19 13:02:17 CEST 2011


On Apr 19, 2011, at 3:46 AM, Michael Bach wrote:

> Dear R Users,
>
> Lets assume I have this data frame:
>
>     x y   z
> 1 1.00 5 0.5
> 2 1.02 5 0.7
> 3 1.04 7 0.1
> 4 1.06 9 0.4
>
> x and y columns are sorted and the values not necessarily integers.  z
> values are not sorted.  Now I would like to create a matrix out of  
> this
> with x as first column values and y as first row values.  Matrix  
> element
> a_11 shall be left NA.  The a_ij should have the z value for the
> corresponding x and y pair.  The result shall be some sort of a grid  
> and
> then e.g. look like:
>
>     [,1] [,2] [,3] [,4] [,5]
> [1,]   NA    5    6    7    9 (y)
> [2,] 1.00  0.5   NA   NA   NA
> [3,] 1.02  0.7   NA   NA   NA
> [4,] 1.04   NA   NA  0.1   NA
> [5,] 1.06   NA   NA   NA  0.4
>      (x)
>
> This example is just for illustration.  The resulting matrix should  
> have
> more numeric values than NA's.
>
> I hope I made myself clear.

Perhaps but only if the third row of your example was incorrectly  
constructed:
 >  dta <- rd.txt("   x y   z
1 1.00 5 0.5
2 1.02 5 0.7
3 1.04 7 0.1
4 1.06 9 0.4")
#rd.txt() is a combo fn of read.table and textConnection

 > mat <- matrix(NA, ncol=NROW(dta)+1, nrow=NROW(dta)+1)
 > mat[2:NROW(mat),1] <- dta[["x"]]
 > mat[1,2:NROW(mat)] <- dta[["y"]]
 > diag(mat) <- c(NA, dta[["z"]])
 > mat
      [,1] [,2] [,3] [,4] [,5]
[1,]   NA  5.0  5.0  7.0  9.0
[2,] 1.00  0.5   NA   NA   NA
[3,] 1.02   NA  0.7   NA   NA
[4,] 1.04   NA   NA  0.1   NA
[5,] 1.06   NA   NA   NA  0.4


> Any hints on how to achieve this?  Is there
> already a function that does it?  All searches I did pointed me to  
> data
> type frame to matrix conversion...
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list