Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading