How to convert entire dataframe to numeric while preserving decimals?

前端 未结 4 638
甜味超标
甜味超标 2020-12-13 04:49

I have a mixed class dataframe (numeric and factor) where I am trying to convert the entire data frame to numeric. The following illustrates the type of data I am working w

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 05:19

    Using dplyr (a bit like sapply..)

    df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))
    

    which gives:

    glimpse(df2)
    Observations: 4
    Variables: 2
    $ a  0.01, 0.02, 0.03, 0.04
    $ b  2, 4, 5, 7
    

    from your df1 which was:

    glimpse(df1)
    Observations: 4
    Variables: 2
    $ a  0.01, 0.02, 0.03, 0.04
    $ b  2, 4, 5, 7
    

提交回复
热议问题