Limiting the number of decimals in a dataframe (R)

后端 未结 4 1834
青春惊慌失措
青春惊慌失措 2021-02-05 08:26

I would like to limit the number of decimals when a data frame is imported. My .txt input have 16 decimals to each row in collumn \"Value\". My dataframe look like that:

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 09:05

    A dplyr solution using mutate_if to check if the columns in the current data frame are numeric then apply the round() function to them

    # install.packages('dplyr', dependencies = TRUE)
    library(dplyr)
    
    DF %>% 
      mutate_if(is.numeric, round, digits = 8)
    #>   NE001358.Log.R.Ratio
    #> 1          -0.09703693
    #> 2           0.13189355
    #> 3           0.06292665
    #> 4           0.29955913
    #> 5          -0.01288043
    #> 6           0.06397440
    #> 7           0.02716694
    #> 8           0.32239536
    #> 9           0.17959129
    
    ### dplyr v1.0.0+
    DF %>% 
      mutate(across(where(is.numeric), ~ round(., digits = 8)))
    #>   NE001358.Log.R.Ratio
    #> 1            -0.097037
    #> 2             0.131894
    #> 3             0.062927
    #> 4             0.299559
    #> 5            -0.012880
    #> 6             0.063974
    #> 7             0.027167
    #> 8             0.322395
    #> 9             0.179591
    

    Created on 2019-03-17 by the reprex package (v0.2.1.9000)

提交回复
热议问题