Adjust number of decimal places in a dataset

Viewed 190

I would like to adjust my table numbers. I would like to leave only two numbers after the comma, that is, instead of leaving 1.31231 it would be 1.31 and so on.

library(DT)
library(dplyr)


Test <- structure(list(date2 = structure(c(18808, 18808, 18809, 18810
), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
coef1 = c(445.23231, 1.31231, 6.32323, 1.232),coef2 = c(8.3231, 3.3432, 1.3233, 6.3233)), row.names = c(NA, 4L), class = "data.frame")

Test<-Test%>%mutate(Sum = rowSums(across(3:last_col()), na.rm = TRUE))
Test <- Test %>% mutate(across(where(is.numeric), ~paste0('US $', .)))
    > Test
       date2 Category         coef1      coef2           Sum
1 2021-06-30      FDE US $445.23231 US $8.3231 US $453.55541
2 2021-06-30      ABC   US $1.31231 US $3.3432   US $4.65551
3 2021-07-01      FDE   US $6.32323 US $1.3233   US $7.64653
4 2021-07-02      ABC     US $1.232 US $6.3233    US $7.5553
3 Answers

Define floor_decimal function as

floor_decimal <- function(x, level=1) round(x - 5*10^(-level-1), level)

Test %>%
  mutate(Sum = rowSums(across(3:last_col()), na.rm = TRUE)) %>%
  mutate(across(where(is.numeric), ~floor_decimal(.x,2))) %>%
  mutate(across(where(is.numeric), ~paste0('US $', .)))


    
       date2 Category      coef1    coef2        Sum
1 2021-06-30      FDE US $445.23 US $8.32 US $453.55
2 2021-06-30      ABC   US $1.31 US $3.34   US $4.65
3 2021-07-01      FDE   US $6.32 US $1.32   US $7.64
4 2021-07-02      ABC   US $1.23 US $6.32   US $7.55
Test %>%
  mutate(sum = rowSums(across(3:last_col()), na.rm = TRUE), 
         across(where(is.numeric), ~sprintf("US $%.2f", .x)))

       date2 Category      coef1    coef2        sum
1 2021-06-30      FDE US $445.23 US $8.32 US $453.56
2 2021-06-30      ABC   US $1.31 US $3.34   US $4.66
3 2021-07-01      FDE   US $6.32 US $1.32   US $7.65
4 2021-07-02      ABC   US $1.23 US $6.32   US $7.56

we can try to use round for two digit decimal in data frame column wise.

Test[,c(3:4)]<- round(Test[,c(3:4)],2)

OR

Test$coef1 <- round(Test$coef1 ,2)

Test$coef2 <- round(Test$coef2 ,2)
Related