【问题标题】:reading 0 in front of numeric在数字前面读 0
【发布时间】:2022-10-24 01:53:36
【问题描述】:
vec1 <- c(26, 12, 13, 20, 9)
vac1 <- decode_vec(vec1)

结果 :

vac1 : "11010" "01100" "01101" "10100" "01001"

我正在将 vac1 更改为数字,但 0 一直消失。

test_1 <- as.numeric(vac1)

结果

11010 1100 1101 10100 1001

我试图用 sprintf() 恢复 0 ,但它将向量重新更改为字符。

test_2 <- sprintf("%05d", test_1)

"11010" "01100" "01101" "10100" "01001"

我想把莫尔斯电码变成数字形式而不会丢失任何 0

【问题讨论】:

  • 您将无法在数值向量中添加前导零。
  • 我同意之前的评论,为什么需要将其设为数字​​?

标签: r character numeric


【解决方案1】:

数字向量不会以 0 前缀打印,但我们可以定义我们自己的 S3 类。我们定义了 as.bin.numeric、as.data.frame.bin、format.bin 和 print.bin 方法。我们还没有定义 [.bin 方法,因此必须将下标值转换回,如下所示。 bin 类在内部存储为普通数字。根据需要定义其他方法。

library(dst)
library(zoo)

as.bin <- function(x, ...) UseMethod("as.bin")
as.bin.numeric <- function(x, ...) structure(x, class = "bin")

as.data.frame.bin <- zoo:::as.data.frame.yearmon

format.bin <- function(x, ...) {
  x <- unclass(x)
  n <- max(floor(log2(x)) + 1)
  base <- rep(2, n)
  sapply(x, function(y) paste0(encode(base, y), collapse = ""))
}

print.bin <- function(x, ...) print(format(x), ...)

现在测试这些

v0 <- c(26, 12, 13, 20, 9)

v <- as.bin(v0)

as.numeric(v)
## [1] 26 12 13 20  9

v
## [1] "11010" "01100" "01101" "10100" "01001"

v + 1
## [1] "11011" "01101" "01110" "10101" "01010"

as.bin(v[1])
## [1] "11010"

data.frame(v = v)
##       v
## 1 11010
## 2 01100
## 3 01101
## 4 10100
## 5 01001

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多