1

I have a data.frame with a column called weight in a factor format, and I have these values:

Weight
8.248
5.365333333333333
5.725333333333337

and I need to convert this to a numeric value, with the same values, only changing the format.

But, when I do this using this code:

dt$New.weight=as.numeric(dt$Weight)

and I get this data.frame:

Weight            New.weight
8.248             2547
5.365333333333333 871
5.725333333333337 958

What I'm doing wrong?

Curious G.
  • 838
  • 8
  • 23
  • Relevant: [How to convert a factor to integer\numeric without loss of information?](https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-integer-numeric-without-loss-of-information) – markus Apr 22 '19 at 18:22

1 Answers1

1

Storage mode of factor is integer, so we when directly apply as.numeric on factor, we get the integer storage mode values instead of the actual values. One option is to convert it through as.character

as.numeric(as.character(dt$Weight))

v1 <- factor(rep(c(21, 24, 32), 2))
as.numeric(v1)
#[1] 1 2 3 1 2 3

as.numeric(as.character(v1))
#[1] 21 24 32 21 24 32
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Perfect, sorry to disturb you. But I can't understand why I need to use `as.character` too? I have several difficulties to understand this! – Curious G. Apr 22 '19 at 18:21