How to read data when some numbers contain commas as thousand separator?

后端 未结 11 1294
情书的邮戳
情书的邮戳 2020-11-22 02:29

I have a csv file where some of the numerical values are expressed as strings with commas as thousand separator, e.g. \"1,513\" instead of 1513. Wh

11条回答
  •  粉色の甜心
    2020-11-22 02:45

    You can have read.table or read.csv do this conversion for you semi-automatically. First create a new class definition, then create a conversion function and set it as an "as" method using the setAs function like so:

    setClass("num.with.commas")
    setAs("character", "num.with.commas", 
            function(from) as.numeric(gsub(",", "", from) ) )
    

    Then run read.csv like:

    DF <- read.csv('your.file.here', 
       colClasses=c('num.with.commas','factor','character','numeric','num.with.commas'))
    

提交回复
热议问题