[R] remove commas in a number when reading a text file

Lee, Eric elee at AIR-WORLDWIDE.COM
Mon Jun 13 22:38:50 CEST 2011


Thanks, Peter and to Joshua Wiley and Peter Alspach for similar comments.  Gsub did the trick.

-----Original Message-----
From: Peter Langfelder [mailto:peter.langfelder at gmail.com] 
Sent: Monday, June 13, 2011 4:35 PM
To: Lee, Eric
Cc: r-help at R-project.org
Subject: Re: [R] remove commas in a number when reading a text file

On Mon, Jun 13, 2011 at 8:48 AM, Lee, Eric <elee at air-worldwide.com> wrote:
> Hello,
>
> I'm running version R x64 v2.12.2 on a 64bit windows 7 PC.  I'm trying to read a text file using read.table where the values have a format like "1,234,567".  What I want is "1234567".  Is there a quick way to strip out the commas?  I can use strsplit and paste, but the file is quite large and would take some time.  Thanks.

You could use gsub. if you have a character string s, use

sWithoutCommas = gsub(",", "", s, fixed = TRUE)

to remove all commas from s.

To do it for a whole table, I would do something like


removeComma= function(s) {gsub(",", "", s, fixed = TRUE)}

tabWithoutCommas = apply(tab, 2, removeComma)

Try it to see if does what you need.

HTH,

Peter



More information about the R-help mailing list