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

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Wed, 16 May 2007 08:20:53 -0500

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

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



R-help_at_stat.math.ethz.ch 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. Received on Wed 16 May 2007 - 13:48:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 16 May 2007 - 15:01:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.