0

I have a vector that contains both integers and numbers with decimal places. I want to only display decimal places as necessary. For example, I have the following vector:

vec <- c(0.01, 0.1, 1, 10)

R currently displays the values as such:

> vec
[1]  0.01  0.10  1.00 10.00

The output I'm looking for would be this:

0.01  0.1  1  10

Thus far, I've only been able to round all values of the vector to the same decimal place. Thanks!

Reb Gray
  • 87
  • 1
  • 4
  • `as.character(vec)` returns `"0.01" "0.1" "1" "10"`. This turns your `numeric` vector into a `character` vector (which I assume is fine since you're asking after output formatting). Is this what you're after? – Maurits Evers Aug 27 '20 at 12:37
  • Welcome to stackoverflow! [This](https://stackoverflow.com/questions/2287616/controlling-number-of-decimal-digits-in-print-output-in-r) might be of interest. – ismirsehregal Aug 27 '20 at 12:42
  • Other options might be: `formatC(vec)` or `prettyNum(vec)`. – GKi Aug 27 '20 at 13:13

1 Answers1

0

We may use an extra S3 class:

print.myNumeric <- function(x) cat(x, sep = "  ")

Compare printing before and after adding the class:

vec
#> [1]  0.01  0.10  1.00 10.00

class(vec) <- c("myNumeric", class(vec))

vec
#> 0.01  0.1  1  10

Basic math preserves the class and the printing:

4 * vec + 1:4
#> 1.04  2.4  7  44
Aurèle
  • 12,545
  • 1
  • 31
  • 49