PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to round numbers in a vector to only show necessary decimals in R?

 August 10, 2022     decimal, r, rounding, vector     No comments   

Issue

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!


Solution

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


Answered By - Aurèle
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing