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
  • 731
  • 3
  • 13
  • 32

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
  • 85,757
  • 12
  • 122
  • 177
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
  • 251,731
  • 20
  • 347
  • 472