Most elegant way to load csv with point as thousands separator in R

后端 未结 2 650
-上瘾入骨i
-上瘾入骨i 2021-01-02 08:16

NB: To the best of my knowledge this question is not a duplicate! All the questios/answers I found are either how to eliminate points from data that are alr

2条回答
  •  失恋的感觉
    2021-01-02 09:03

    Adapted from this post: Specify custom Date format for colClasses argument in read.table/read.csv

    #some sample data
    write.csv(data.frame(a=c("1.234,56","1.234,56"),
                         b=c("1.234,56","1.234,56")),
              "test.csv",row.names=FALSE,quote=TRUE)
    
    #define your own numeric class
    setClass('myNum')
    #define conversion
    setAs("character","myNum", function(from) as.numeric(gsub(",","\\.",gsub("\\.","",from))))
    
    #read data with custom colClasses
    read_data=read.csv("test.csv",stringsAsFactors=FALSE,colClasses=c("myNum","myNum"))
    #let's try whether this is really a numeric
    read_data[1,1]*2
    
    #[1] 2469.12
    

提交回复
热议问题