0

I have a dataframe that looks a bit like this:

Analyte  Value     
Fe       60.3203 
Sio2     2.3003 
As       0.5564

I want to round the values column to different decimals places depending on its value. That is if the value is > 1 then I want to show 2 decimal places, and if it is < 1 I want to round to 3 decimal places Is it possible to apply this to an R dataframe?

I have tried:

df$value <- if_else(df$value >1.0, round(df$value, digits =3), round(df$value, digits =2))

and

df$value <- if_else(df$value >1.0, format(round(df$value, nsmall =3)), format(round(df$value, nsmall =2)))

I have also tried a few variations of the above two options but I always end up with the whole column being rounded to the same number of decimal places.

I suspect this type of more suited for some sort of graphical type feature when presenting the table?

Karthik S
  • 11,348
  • 2
  • 11
  • 25
Spooked
  • 586
  • 1
  • 4
  • 16

1 Answers1

1

You can use sprintf to control the decimal places if this is for display purpose :

with(df, ifelse(Value > 1, sprintf("%.3f",Value), sprintf("%.2f",Value)))
#[1] "60.320" "2.300"  "0.56" 

You were close with format and round, you can do :

with(df, trimws(ifelse(Value > 1, format(round(Value, 3), nsmall = 3), 
                                  format(round(Value, 2), nsmall = 2))))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213