1

When a vector a is transformed to a factor and transformed back to numeric, why does a prints out different elements?

a = c(9, 10, 11, 12)
a = as.factor(a)
a
> a
[1] 9  10 11 12
Levels: 9 10 11 12

a = as.numeric(a)
a
> a
[1] 1 2 3 4
shsh
  • 684
  • 1
  • 7
  • 18

1 Answers1

1

Here, the values showed by direction conversion is the integer storage values. We need to either convert it to character and then to numeric

a1 <- as.numeric(as.character(a))

Or use a faster option with levels

a1 <- as.numeric(levels(a)[a])
a1
#[1]  9 10 11 12
class(a1)
#[1] "numeric"
akrun
  • 874,273
  • 37
  • 540
  • 662