0

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.

5
  • as.numeric may do what you wish? Commented Feb 24, 2014 at 9:14
  • what u exact want to do? amount type 20000 abc Commented Feb 24, 2014 at 9:16
  • 3
    when reading the data, you can set dec=",", which will read data as numeric values (comma will separate decimals) and then you can multiple them by 1000 to get the correct values Commented Feb 24, 2014 at 9:16
  • cant use as.numeric as the data is in level. @Zbynek where i should put dec=","? Thanks Commented Feb 24, 2014 at 9:23
  • read.csv('path.to.file', dec=',') Commented Feb 24, 2014 at 9:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help it do exactly what i need. <br/> while i tried data<-read.csv("rev3.csv","dec=","). It do not work. Maybe it is because i got two attributes that another one besides value is a character "Name".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.