Skip to content

how to force years as.numeric?

2 messages · Viktor Nagy, Marc Schwartz

#
Hi,

My next problem is that I have a data frame with an years column. This
column for some reason is recognised as factor instead of being
numeric. The years go from 1970 to 2007. When I convert it to numeric
with as.numeric then it goes from 1 to 38. Is there a way to convert
it with saving its "levels"?

This would be actually important as I am affraid of converting my real
values that are recognised as factors as well.

Thanks, Viktor
#
on 12/10/2008 06:54 PM Viktor Nagy wrote:
Viktor,

I would be concerned as to why a column that presumably only contains
numeric values is being coerced to a factor to begin with. That would
normally only occur when a column contains non-numeric characters.

read.table(), for example, uses type.convert() internally to do that and
the logic for the type coercion from a character vector is pretty
straight-forward.

Thus, you may have corrupted year values or at least corrupted
characters in that particular column. I would recommend reviewing that
data to get a sense of what is going on before proceeding.

In general, FAQ 1.10 "How do I convert factors to numeric?" covers the
process of converting factors containing numeric characters back to
their numeric values:

http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f

HTH,

Marc Schwartz