如何在R中进行数字系统之间的转换?

5
我注意到有一个内置函数可用于将十进制转换为罗马数字的相对抽象的用法(将罗马数字转换为R中的数字),但我找不到内置的方法来将十进制转换为其他类似的系统,例如3进制或11进制。 我看到二进制和十六进制(基数16)得到了很好的支持,但是否有用于将任意定位数字系统进行转换的包。
我可以创建这样的软件包,但我怀疑它已经存在,只是我的谷歌搜索能力不足而已?

2
看起来 cwhmisc 包的 4.0 版本适合您使用:https://www.rdocumentation.org/packages/cwhmisc/versions/4.0/topics/convert请查阅 xToBase 函数。 - StatsStudent
同时,http://www.rebol.org/documentation.r?script=base-convert.r - Ben Bolker
1
顺便说一句,在SO上,“搜索软件包/软件资源”是不相关的话题;为了避免关闭,您可以重新表述问题,而不是“是否有一个软件包可以...”,而是“我想在数字系统之间进行转换”。 - Ben Bolker
1个回答

10
你可以编写自己的S3类:
base <- function(b, base = 10)
{
  base <- as.integer(base)
  if(base > 36 | base < 2) stop("'base' must be between 2 and 36.")
  
  structure(lapply(b, function(x) 
    {
      n   <- ceiling(log(x, base))
      vec <- numeric()
      val <- x
      
      while(n >= 0)
      {
        rem <- val %/% base^n
        val <- val - rem * base^n
        vec <- c(vec, rem)
        n <- n - 1
      }
      
      while(vec[1] == 0 & length(vec) > 1) vec <- vec[-1]
      structure(x, base = base, representation = vec) 
    }), class = "base")
}

需要使用formatprint方法:
format.base <- function(b, ...) 
{
  sapply(b, function(x) 
    {
      glyphs <- c(0:9, LETTERS)
      base   <- attr(x, "base")
      vec    <- attr(x, "representation")
      paste0(glyphs[vec + 1], collapse = "")
    })
}

print.base <- function(b, ...) print(format(b), quote = FALSE)

我们还需要确保数学运算正常工作:
Ops.base <- function(e1, e2) {
  base <- attr(e1[[1]], "base")
  e1   <- unlist(e1)
  e2   <- unlist(e2)
  base(NextMethod(.Generic), base)
}

Math.base <- function(e1, e2) {
  base <- attr(e1[[1]], "base")
  e1   <- unlist(e1)
  e2   <- unlist(e2)
  base(NextMethod(.Generic), base)
}

如果您想在数据框(Data Frame)内使用它,则需要使用as.data.frame方法:

as.data.frame.base <- function(b, ...) 
{
  structure(list(b),  
            class = "data.frame", 
            row.names = seq_along(b))
}

以下是相关行为的允许:

data.frame(binary = base(1:20, 2), hex = base(1:20, 16), oct = base(1:20, 8))
#>    binary hex oct
#> 1       1   1   1
#> 2      10   2   2
#> 3      11   3   3
#> 4     100   4   4
#> 5     101   5   5
#> 6     110   6   6
#> 7     111   7   7
#> 8    1000   8  10
#> 9    1001   9  11
#> 10   1010   A  12
#> 11   1011   B  13
#> 12   1100   C  14
#> 13   1101   D  15
#> 14   1110   E  16
#> 15   1111   F  17
#> 16  10000  10  20
#> 17  10001  11  21
#> 18  10010  12  22
#> 19  10011  13  23
#> 20  10100  14  24

并且:

x <- base(67, 11)
y <- base(35, 2)
x + y
#> [1] 93

base(x + y, 10)
#> [1] 102

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接