[R] more woes trying to convert a data.frame to a numerical matrix

Marc Schwartz marc_schwartz at comcast.net
Wed May 16 15:20:53 CEST 2007


On Wed, 2007-05-16 at 09:05 -0400, Andrew Yee wrote:
> Thanks for the suggestion.
> 
> However, I've tried sapply and data.matrix.
> 
> The problem is that it while it returns a numeric matrix, it gives
> back:
> 
> 1 1 1
> 2 2 2
> 3 3 3
> 
> instead of
> 
> 1 2 3 
> 4 5 6
> 7 8 9
> 
> The latter matrix is the desired result
> 
> Thanks,
> Andrew

OK.  One more time with gusto...

We need to coerce the values to character first, since they are read in
as factors and the results that we are seeing are the numeric values of
the factor levels and not the numeric values themselves.

Oy...

mat <- sapply(sample.data[-1, -1], 
              function(x) as.numeric(as.character(x)))

rownames(mat) <- rownames(sample.data[-1, -1])

> mat
  x y z
2 1 2 3
3 4 5 6
4 7 8 9

> str(mat)
 num [1:3, 1:3] 1 4 7 2 5 8 3 6 9
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "2" "3" "4"
  ..$ : chr [1:3] "x" "y" "z"


It looks like data.matrix() does not do the character coercion
internally, so the above approach would seem to be better.

Sorry about that.

Another alternative would be to use the modifications to the read.csv()
function call that I referenced initially and then use the result for
your subsequent manipulations.

Marc



More information about the R-help mailing list