How to read csv file in R where some values contain the percent symbol (%)

后端 未结 4 595
面向向阳花
面向向阳花 2020-11-30 14:18

Is there a clean/automatic way to convert CSV values formatted with as percents (with trailing % symbol) in R?

Here is some example dat

4条回答
  •  無奈伤痛
    2020-11-30 14:45

    There is no "percentage" type in R. So you need to do some post-processing:

    DF <- read.table(text="actual,simulated,percent error
    2.1496,8.6066,-300%
    0.9170,8.0266,-775%
    7.9406,0.2152,97%
    4.9637,3.5237,29%", sep=",", header=TRUE)
    
    DF[,3] <- as.numeric(gsub("%", "",DF[,3]))/100
    
    #  actual simulated percent.error
    #1 2.1496    8.6066         -3.00
    #2 0.9170    8.0266         -7.75
    #3 7.9406    0.2152          0.97
    #4 4.9637    3.5237          0.29
    

提交回复
热议问题