useR
useR

Reputation: 3082

Change numeric format in R

How can I change the value 20,000 to 20000 in R? In my case, I have a CSV file where column A is a value with format xx,xxx and column B is a group name.

So

data[,1]
[1] 203,472.40 226,433.70 ...
100 Levels: 101,051.40 103,662.70 ...

The numerical value is a factor instead of numeric.

I to convert data[,1] to

[1] 203472.40 226433.70 ...

I've tried as.numeric, but this doesn't work with factors.

Upvotes: 0

Views: 691

Answers (1)

csgillespie
csgillespie

Reputation: 60462

To answer your question, you need to:

  1. Convert the factor to character - as.character
  2. Remove the comma - gsub
  3. Convert to numeric - as.numeric

So

x = factor(c("203,472.40","226,433.70"))
as.numeric(gsub(",", "", as.character(x)))

Of course, you should try and fix the problem (if possible) up-stream, i.e. using dec in read.csv

Upvotes: 2

Related Questions