Green Demon
Green Demon

Reputation: 4208

Casting data into integer/nu changes the data

I have a problem casting data from string into integer.

For example, the original data looks like this

orderdt[1:10,2]

[1] 71004 13943 11337 9647  9363  6836  5957  5167  4963  4850  

But when I cast it into double like this it changes to completely different numbers

as.numeric(orderdt[1:10,2])

[1]  854  164   82 1069 1051  823  724  636  613  600

Originally I cast the column (some 1 mill rows) into double, and most of the lower part were converted, only the first 300 or so were screwed up this way. Do you know why this happened or how to fix it?

Please help.

Upvotes: 1

Views: 78

Answers (1)

csgillespie
csgillespie

Reputation: 60452

Almost certainly you have a factor. To check, use:

is.factor(orderdt[1:10,2])

If it is a factor, than

as.numeric(as.character(is.factor(orderdt[1:10,2])))

should do what you expect.

The question you now (probably) have is why do I have a factor? Without further information that's tricky to know, but the usual reason is you've loaded in your data (say via a csv file) and one of your "numbers" isn't a number. For example, you have "1,12" rather than "1.12"

Upvotes: 4

Related Questions