[R] hello

rolf at math.unb.ca rolf at math.unb.ca
Thu Apr 19 16:17:07 CEST 2007


francois.morneau at ifn.fr wrote:

> ?as.numeric

in response to

> ok how can I do to cancel le function factor for the moment ican't do
> this and I'm stuck with my problem for exemple

        .......

        <snip>

        The use of as.numeric() to convert a factor to a numeric
        vector is fraught with peril.

        E.g.

        > f <- factor(rep(2*(1:5),3))
        > f
         [1] 2  4  6  8  10 2  4  6  8  10 2  4  6  8  10
        Levels: 2 4 6 8 10
        > as.numeric(f)
         [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

        which is probably not what one was expecting or wanting.

        However you *can* get what you want:

        > as.numeric(as.character(f))
         [1]  2  4  6  8 10  2  4  6  8 10  2  4  6  8 10

                                cheers,

                                        Rolf Turner
                                        rolf at math.unb.ca

P.S. To save myself key-strokes I have written a wee function

        f2n <- function(x){as.numeric(as.character(x))}

                                        R. T.



More information about the R-help mailing list