0

I am new to R. I am trying to set y equal to 3 decimal place of x so

x=3.45678
round(x, digits = 3)
x

I get x = 3.457, And want to set y equal to 7 in this case.

AK9309
  • 761
  • 3
  • 13
  • 33

2 Answers2

2

Keep it all numeric, which should be reasonably quick:

nthdigit <- function(x,n) {
  m <- round(x,digits=n)*10^(n-1)
  (m - floor(m))*10
}

nthdigit(x,3)
#[1] 7

Timings seem reasonable over here:

x <- rep(3.45678,1e7)  # 10 million cases
system.time(nthdigit(x,3))
#   user  system elapsed (seconds)
#   1.17    0.00    1.19 
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Thank you. I can't figure out how would I do the same thing but without rounding procedure. Just take the digit that I want and set it equal to a variable – AK9309 Jan 30 '15 at 01:48
  • @Artem : `nthdigit <- function(x,n) { m <- floor(x*10^n)/10;(m - floor(m))*10}` – thelatemail Jan 30 '15 at 02:00
0

Deleting all the digits and decimal point prior to the nth-rounded last digit, with optional reversion to numeric:

> sub("\\d*\\.\\d{2}","", round(x,3) )
[1] "7"
> as.numeric( sub("\\d*\\.\\d{2}","", round(x,3) ) )
[1] 7
IRTFM
  • 258,963
  • 21
  • 364
  • 487