Example:
library(Rmpfr)
x.mpfr <- 1:11 + Rmpfr::mpfr(1.e20, precBits = 1000)
var(x.mpfr)
Error in var(x.mpfr) : is.atomic(x) is not TRUE
Question:
How to make the function var()
run with the mpfr vector x.mpfr
?
To be precise, here the var()
is a demonstration example. In general, my question is, how to use a function with mpfr data when the type of mpfr triggered the atomic error? Is there any convenient solution of doing it without rewriting a function with mpfr embeded?
If you want to use numbers of class "mpfr"
and base R functions give that error, the only way I know of is to write your own functions.
In the example below I have made VAR
and SD
generic, so that calls of the type fun(x)
work.
See also my answer to this R-Help thread, mirrored here.
library(Rmpfr)
#> Loading required package: gmp
#>
#> Attaching package: 'gmp'
#> The following objects are masked from 'package:base':
#>
#> %*%, apply, crossprod, matrix, tcrossprod
#> C code of R package 'Rmpfr': GMP using 64 bits per limb
#>
#> Attaching package: 'Rmpfr'
#> The following object is masked from 'package:gmp':
#>
#> outer
#> The following objects are masked from 'package:stats':
#>
#> dbinom, dgamma, dnbinom, dnorm, dpois, dt, pnorm
#> The following objects are masked from 'package:base':
#>
#> cbind, pmax, pmin, rbind
VAR <- function(x, ...) UseMethod("VAR")
VAR.mpfr <- function(x, na.rm = FALSE) {
if(na.rm) x <- x[!is.na(x)]
n <- length(x)
x.bar <- mean(x)
(sum(x^2) - n*x.bar^2)/(n - 1)
}
SD <- function(x, ...) UseMethod("SD")
SD.mpfr <- function(x, na.rm = FALSE) sqrt(VAR(x, na.rm = na.rm))
x.mpfr <- 1:11 + Rmpfr::mpfr(1.e20, precBits = 1000)
mean(x.mpfr)
#> 1 'mpfr' number of precision 1000 bits
#> [1] 100000000000000000006
VAR(x.mpfr)
#> 1 'mpfr' number of precision 1000 bits
#> [1] 11
sd(x.mpfr)
#> [1] 0
SD(x.mpfr)
#> 1 'mpfr' number of precision 1000 bits
#> [1] 3.31662479035539984911493273667068668392708854558935359705868214611648464260904384670884339912829065090701255784952745659227543978485754747977932493304472884730287397482865568257739444461209804447719311235714413297152109883266049571003724852073810682080748758396589499452515931529840068271971051828955738
Created on 2023-04-18 with reprex v2.0.2