Changing number of decimal places on selected values

Hi Folks,

Can you help me control number of decimal places on selected values in a dataframe?

Here is a simple data frame.
df <- data.frame(Product = c('One', 'Two', 'Three'),
Cost = c(1.556, 9.235, 5.145),
Margin = c(0.235, 5.894, 11.457)
)

I can convert values to two decimal places using this code
df_1 <- df |> mutate(across(where(is.numeric), round, 2))

But, for values less than or equal to 10, I need two decimal places, and for values greater than 10 I need zero decimal places.

Your help will be greatly appreciated.

Thanks, Jenny

Does this do what you want?

library(tidyverse)
DF <- data.frame(A = c(2.45621, 12.908), B = c("Z","U"), C = c(55.432, 0.9834))
DF
#>          A B       C
#> 1  2.45621 Z 55.4320
#> 2 12.90800 U  0.9834
DF <- DF |> 
  mutate(across(where(is.numeric), ~ifelse(.x <= 10, round(.x,2), round(.x, 0))))
DF
#>       A B     C
#> 1  2.46 Z 55.00
#> 2 13.00 U  0.98

Created on 2024-02-25 with reprex v2.0.2

1 Like

Much appreciated. That works fine.

How would I apply it to numeric column A, but not numeric column C in your example?

If you want to change only column A, use this code:

DF <- DF |>  mutate(A = ifelse(A <= 10, round(A, 2), round(A, 0)))
1 Like

Thanks very much. Your help was great!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.