Search code examples
rformatdecimalroundingscientific-notation

Using format() in R to convert numeric value to scientific notation after rounding


A small snippet of my overall code is to round a given vector to a specified number of decimal places. The rounded value is then converted to standard notation, e.g. "1.2e-01".

The following does the rounding which works fine.

values <- c(0.1234, 0.5678)
dig <- 2
rounded_vals <- round(values, dig) %>% str_trim()

When I run the following code I expect to see the same output for both lines.

format(rounded_vals, scientific = TRUE)
format(c(0.12, 0.56), scientific = TRUE)

What I actually get is:

> format(rounded_vals, scientific = TRUE)
[1] "0.12" "0.57"
> format(c(0.12, 0.56), scientific = TRUE)
[1] "1.2e-01" "5.6e-01"

Why doesn't format(rounded_vals, scientific = TRUE) return the same output and how can I adjust the code to do so?

Would appreciate any input :)

Edit: I missed out a bit of code that was causing the problem - seems to be that str_trim() covnerts to character.


Solution

  • I think rounded_vals might have been stored as character values. Try converting them to numbers using as.numeric() and then put it into the format() function.