R: Converting data frame of percentages from factor to numeric

前端 未结 4 466
失恋的感觉
失恋的感觉 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:02

    Here is an option using set from data.table, which would be faster for big datasets as the overhead of [.data.table is avoided

    library(stringi)
    library(data.table)
    
    setDT(df)
    for(j in 2:ncol(df)){
         set(df, i=NULL, j=j, value= as.numeric(stri_extract(df[[j]], regex='\\d+')))
    }
    
    df
    #     Year v1 v2 v3 v4
    #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
    

提交回复
热议问题