Limiting the number of decimals in a dataframe (R)
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)
Here is.num
is TRUE
for numeric columns and FALSE
otherwise. We then apply round
to the numeric columns:
is.num <- sapply(DF, is.numeric)
DF[is.num] <- lapply(DF[is.num], round, 8)
If what you meant was not that you need to change the data frame but just that you want to display the data frame to 8 digits then it's just:
print(DF, digits = 8)
In dplyr 1.0.0 and later one can use across
within mutate
like this:
library(dplyr)
DF %>% mutate(across(where(is.numeric), ~ round(., 8)))