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

后端 未结 11 1432
情书的邮戳
情书的邮戳 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:42

    A very convenient way is readr::read_delim-family. Taking the example from here: Importing csv with multiple separators into R you can do it as follows:

    txt <- 'OBJECTID,District_N,ZONE_CODE,COUNT,AREA,SUM
    1,Bagamoyo,1,"136,227","8,514,187,500.000000000000000","352,678.813105723350000"
    2,Bariadi,2,"88,350","5,521,875,000.000000000000000","526,307.288878142830000"
    3,Chunya,3,"483,059","30,191,187,500.000000000000000","352,444.699742995200000"'
    
    require(readr)
    read_csv(txt) # = read_delim(txt, delim = ",")
    

    Which results in the expected result:

    # A tibble: 3 × 6
      OBJECTID District_N ZONE_CODE  COUNT        AREA      SUM
                                 
    1        1   Bagamoyo         1 136227  8514187500 352678.8
    2        2    Bariadi         2  88350  5521875000 526307.3
    3        3     Chunya         3 483059 30191187500 352444.7
    

提交回复
热议问题