[R] as.numeric : what goes wrong?

Uwe Ligges ligges at statistik.uni-dortmund.de
Fri Aug 24 13:04:31 CEST 2007



Wolfgang Polasek wrote:
> I have a character vector j1 created from dimnames and want it to convert it
> to numeric.
> Like the first element:
> 
>> j1[1]
>   f896
> 1  896


Probably this is a factor?


>> as.numeric(j1[1])
> [1] 1990

And this is the number the factor level 896 has been coded with.


?factor tells us:

"The interpretation of a factor depends on both the codes and the 
"levels" attribute. Be careful only to compare factors with the same set 
of levels (in the same order). In particular, as.numeric applied to a 
factor is meaningless, and may happen by implicit coercion. To “revert” 
a factor f to its original numeric values, as.numeric(levels(f))[f] is 
recommended and slightly more efficient than as.numeric(as.character(f))."

Hence as.numeric(levels(f))[f] is the way to go.

Best,
Uwe Ligges



> why is it not 896 as it should be?
> This is true fr the whole vector.
> 
> Thanks
> W.P.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.



More information about the R-help mailing list