[R] Converting dollar value (factors) to numeric

laihaobo contact at Laihaobo.com
Tue Feb 5 20:31:25 CET 2013


Both Greg and David's methods are working fine for me under R version 2.15.2
without warnings.

setClass("Currency")
setAs("character", "Currency",
    function(from) as.numeric(gsub("[$,]","",sub("$","",from, fixed=TRUE))))
# method 2: ",|\\$", working as desired 
setClass("Currency2")
setAs("character", "Currency2",
    function(from) as.numeric(gsub(",|\\$","",sub("$","",from,
fixed=TRUE))))

hm.prc.new <- read.table("./Data/SalesPrcNewHms.txt", header = T, sep = " ",
quote = "\"'",
           dec = ".", colClasses=c(Median="Currency",Average="Currency2"))  

> summary(hm.prc.new)
     Period         Median          Average      
 Min.   :1963   Min.   : 18000   Min.   : 19300  
 1st Qu.:1975   1st Qu.: 38450   1st Qu.: 41675  
 Median :1986   Median : 98250   Median :119550  

Raw data are in the format:
Period Median Average
1963 $18,000 $19,300
1964 $18,900 $20,500
1965 $20,000 $21,500
.....

Haobo




--
View this message in context: http://r.789695.n4.nabble.com/Converting-dollar-value-factors-to-numeric-tp2130536p4657634.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list