Re: [R] How to change the class of data?

From: Charilaos Skiadas <cskiadas_at_gmail.com>
Date: Thu, 12 Jun 2008 03:42:23 -0400

Seeing how there have been three wrong answers so far, I should point out that:

  1. This is an FAQ: http://cran.r-project.org/doc/FAQ/R-FAQ.html#How- do-I-convert-factors-to-numeric_003f
  2. Most of the other methods suggested so far fail if the example x used is not of the form 1:n. The only reason they happen to work, is that in that case the levels coincide with their labels.

 > x<-factor(8:5)
 > as.numeric(levels(x))
[1] 5 6 7 8
 >
 > as.numeric(x)
[1] 4 3 2 1
 > class(x) <- "numeric"
 > x+1
[1] 5 4 3 2
attr(,"levels")
[1] "5" "6" "7" "8"

Haris Skiadas
Department of Mathematics and Computer Science Hanover College

On Jun 12, 2008, at 3:07 AM, anna freni sterrantino wrote:

> Hi Selina,
> try ?as.numeric,
>
> small example
> a=c(1,2,3,4,5)
> b=as.factor(a)
> class(b)
>
> c=as.numeric(b)
> class(c)
>

> in the case of a matrix of factor,try
> apply(matrix,1, as.numeric)
>
> Cheers
>
> A.
>
>
> ----- Messaggio originale -----
> Da: Qman Fin <finosaur_at_gmail.com>
> A: r-help_at_r-project.org
> Inviato: Giovedý 12 giugno 2008, 8:24:08
> Oggetto: [R] How to change the class of data?
>
> Hi all,
>
> I have some data x, which are actualy consisted of numerical
> enties. But the
> class of this matrix is set to be "factor" by someone else. I used
> "class(x)", it turns out to be "factor". So I can not calculate them.
>
> How can I turn them into numerical data so that I can apply math
> operations
> on them? Thanks a lot for your help.
>
> Selina
>



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. Received on Thu 12 Jun 2008 - 07:50:20 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 Sat 28 Jun 2008 - 15:31:01 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.

list of date sections of archive