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

Sunday, August 7, 2022

[FIXED] How do you isolate the digits following a decimal in R?

 August 07, 2022     decimal, digit, isolation, r, truncated     No comments   

Issue

For example: I have the number 123.456 and want to return 456.

The function trunc() basically isolates (truncates) the numbers before the decimal.

Is there a function to isolate just the digits after the decimal?

Two follow-up questions:

  1. Is there a way to do this without writing out the regex?

  2. What if I want to maintain the sign? For example, if I wanted to (reverse) truncate -123.456 to -456.


Solution

Using the modulo operator (%%) with 1 as the devisor works I guess. It does successfully isolate the numbers following the decimal, but leaves the decimal:

123.456 %% 1
[1] 0.456

However it only works for positive numbers in that the sign is not preserved nor are the proper numbers reported (b/c of modulo operator's functionality):

-123.456 %% 1
[1] 0.544  #not what is wanted

Including abs() fixes that issue, but doesn't help report sign. Sign could be included by adding:

sign(x) * (abs(x) %% 1)

If we really wanted to report just the digits after the decimal (i.e., excluding the 0 and the decimal), we could do the following (presented in 2 steps for clarity):

x <- -123.456
y <- sign(x) * (abs(x) %% 1)
as.numeric(gsub("0.","",y))
[1] -456  #as desired from part 2 in the OP


Answered By - theforestecologist
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • 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