R: Converting data frame of percentages from factor to numeric

前端 未结 4 468
失恋的感觉
失恋的感觉 2021-01-22 15:50

Running into issues converting a data frame into R.

I have a bunch of columns that were read as factors and have % symbols with them.

I

4条回答
  •  [愿得一人]
    2021-01-22 16:05

    Here is a one line solution that assumes the data is in fixed width columns. I needed to remove the first row of names since all the columns did not have names. The widths of columns are specified as integers (with negative meaning to skip that many characters.) It also changes the column classes to numeric during the read.

    your data
    
    1 12-Oct        0%      0%      39%      14%
    2 12-Nov        0%      6%      59%       4%
    3 12-Dec       22%      0%      37%      26%
    4 13-Jan       45%      0%      66%      19%
    5 13-Feb       28%     39%      74%      13%
    
    the R one-line script
    
    adf <- read.fwf(file="a.dat",widths=c(-8,9,-1,7,-1,8,-1,8),colClasses=rep("numeric",4))
    
    output result (first col provided by R to count the rows)
    
      V1 V2 V3 V4
    1  0  0 39 14
    2  0  6 59  4
    3 22  0 37 26
    4 45  0 66 19
    5 28 39 74 13
    

提交回复
热议问题