0
votes

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!

1
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
Welcome to stackoverflow! This might be of interest.ismirsehregal
Other options might be: formatC(vec) or prettyNum(vec).GKi

1 Answers

0
votes

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