[R] How do I coerce numeric factor columns of data frame to vector?
Na Li
nali at biostat.umn.edu
Tue Sep 9 17:15:22 CEST 2003
On 9 Sep 2003, Michael A. Miller outgrape:
> > > > > > "Thomas" == Thomas W Blackwell <tblackw at umich.edu> writes:
>
> > Michael - Because these columns are factors to begin with,
> > using as.numeric() alone will have unexpected results. See
> > the section "Warning:" in help("factor").
>
> Ah, thanks for pointing that out. When I've used as.numeric on
> factors, it is usually because I've explicitly made a numeric
> variable a factor. I can see where something that I think aught
> to be numeric would be interpreted as a factor, say due to an
> error in formatting an input file. If I do something like this:
>
> x <- some numeric array
> f <- factor(x)
> y <- as.numeric(x)
>
> is there a possibility of y not equalling x? If x really is
> numeric that is.
> x <- c(1, 3, 1)
> y <- factor (x)
> y
[1] 1 3 1
Levels: 1 3
> as.numeric (y)
[1] 1 2 1
I don't know a good way to convert it back however, except
> as.numeric (levels (y)[as.numeric (y)])
[1] 1 3 1
which is a bit awkward.
Michael
More information about the R-help
mailing list