Home > Back-end >  How do you convert large hexadecimal values to decimal values in R when passing a vector with missin
How do you convert large hexadecimal values to decimal values in R when passing a vector with missin

Time:01-07

In R you can use the strtoi() function to convert a hexadecimal value to a decimal value,

strtoi(c("14A", "15", NA_character_), 16L)

# [1] 330  21  NA

But when you provide more digits then the strtoi function starts to overflow and returns NA instead of the converted value.

strtoi(c("49EA72A5000"), 16L)

# [1] NA

The Rmpfr::mpfr() function appears to be able to handle larger output values

Rmpfr::mpfr(c("49EA72A5000"), base = 16)

# 1 'mpfr' number of precision  44   bits 
# [1] 5079455911936

but it does not handle missing character values very well and throws an error when the missing value is now part of the vector.

Rmpfr::mpfr(c("49EA72A5000", NA_character_), base = 16)

# Error in if ((base == 2 && any(i <- tolower(substr(x, 1L, 2L)) == "0b")) ||  : 
# missing value where TRUE/FALSE needed

The function does appear to handle the logical missing value

Rmpfr::mpfr(NA, base = 16)

# 1 'mpfr' number of precision  2   bits 
# [1] NaN

Is there another package in R that converts large digit hexidecimal values to decimal values and has appropriate error handing? The output does not need to be an integer but could be numeric or character.

Or is there an option that can be passed to the mpfr() function to change how it deals with missing values?

CodePudding user response:

You can make your own wrapper for appropriate missing value handling. For instance:

mpfr_na <- function(x, base)
{
  x[is.na(x)] = NaN
  Rmpfr::mpfr(x, base = base)
}

mpfr_na(c("49EA72A5000"), base = 16)
# [1] 5079455911936

mpfr_na(c("49EA72A5000", NA_character_), base = 16)
# [1] 5079455911936           NaN

mpfr_na(c("49EA72A5000", NA), base = 16)
# [1] 5079455911936           NaN

mpfr_na(c("49EA72A5000", NaN), base = 16)
# [1] 5079455911936           NaN

Does this solve your issue?

  •  Tags:  
  • r
  • Related