Learn R Programming

Ecfun (version 0.2-2)

parseCommas: Convert character string with Dollar signs and commas to numerics

Description

as.numeric of character strings after suppressing commas and dollar signs. This is a generalization of parseDollars.

Usage

parseCommas(x, pattern='\\$|,', replacement='',
        acceptableErrorRate=0, ...)
# S3 method for default
parseCommas(x, pattern='\\$|,', replacement='',
        acceptableErrorRate=0, ...)
# S3 method for data.frame
parseCommas(x, pattern='\\$|,', replacement='',
        acceptableErrorRate=0, ...)

Arguments

x

vector of character strings to be converted to numerics

pattern

regular expression to be replaced by replacement

replacement

Character string to substitute for each occurrence of pattern

acceptableErrorRate

number indicating the proportion of new NAs to that can be introduced and still assume it's numeric

optional arguments to pass to gsub

Value

Numeric vector converted from the character strings in x or a data.frame with columns that are obviously numbers in character format converted to numerics.

Details

as.numeric(gsub(x, ...))

The data.frame method outputs another data.frame with character or factor columns converted to numerics using parseDollars whenever that can be done without creating NAs.

See Also

gsub as.numeric parseDollars

Examples

Run this code
# NOT RUN {
##
## 1.  a character vector
##
X2 <- c('-$2,500', '$5,000.50')
x2 <- parseDollars(X2)

# }
# NOT RUN {
all.equal(x2, c(-2500, 5000.5))
# }
# NOT RUN {
##
## A data.frame
##
chDF <- data.frame(let=letters[1:2], Dol=X2, dol=x2)
numDF <- parseCommas(chDF)

chkDF <- chDF
chkDF$Dol <- x2
# }
# NOT RUN {
all.equal(numDF, chkDF)
# }

Run the code above in your browser using DataLab