[R] Converting factors back to numbers. Trouble with SPSS importdata

Paul Johnson pauljohn32 at gmail.com
Mon Feb 20 01:53:42 CET 2006


On 2/19/06, Robert W. Baer, Ph.D. <rbaer at atsu.edu> wrote:
> Quoted directly from the FAQ (although granted I need to look this up over
> and over, myself.  Would that it had a easily remembered wrapper function):
> 7.10 How do I convert factors to numeric?
> It may happen that when reading numeric data into R (usually, when reading
> in a file), they come in as factors. If f is such a factor object, you can
> use
>
>      as.numeric(as.character(f))
> to get the numbers back. More efficient, but harder to remember, is
>
>      as.numeric(levels(f))[as.integer(f)]

I don't think I have that problem described in the FAQ.  I've had that
before, though.

Observe. Here's the original thing:

> eldatfac$HAPPY[1:10]
 [1] Happy      Happy      Very happy Happy      Very happy Very happy
 [7] Happy      Very happy Happy      Very happy
6 Levels: Not happy at all Not very happy Happy Very happy ... Refused

Here's the result of the first thing you cite from the FAQ

> as.numeric(as.character(eldatfac$HAPPY))[1:10]
 [1] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion

Here's the second thing from the FAQ

> as.numeric(levels(eldatfac$HAPPY))[as.integer(eldatfac$HAPPY)]
 [1] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion

What am I missing here?

--
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas




More information about the R-help mailing list