【问题标题】:R Convert double to string r without converting to scientificR将double转换为字符串r而不转换为科学
【发布时间】:2021-11-05 14:40:10
【问题描述】:

有一个场景,我有一个冗长的(12 位)索引值作为双精度值读入 r。我需要将此与其他一些标识符联系起来,但 mutate(x = as.character(x)) 转换为科学格式:

index <- c(123000789000, 123456000000, 123000000012)
concact_val <- c("C", "A", "B")

df <- 
  bind_cols(
    as_tibble(index),
    as_tibble(concact_val)
  )

df %>%
  mutate(index = as.character(index))

这个输出:

index   concact_val
1.23e11 C
1.23e11 A
1.23e11 B

而理想情况下我希望能够做到这一点:

df %>%
  mutate(index = as.character(index),
         index = paste0(concact_val, index)) %>%
  select(-concact_val)

输出:

index
C123000789000
A123456000000
B123000000012

有没有办法解决这个问题?在这个例子中,我为索引创建了一个向量,但是在我正在读取的帧中,它通过 API 被读取为双精度(不幸的是,我无法在读取之前更改 col 类型,它的读取方式不同比read_csv)。

【问题讨论】:

  • 您可以使用options(scipen = 999) 或使用gmp 转换整数

标签: r string type-conversion double tidyverse


【解决方案1】:

使用sprintf:

df %>%
  mutate(result = sprintf("%s%0.0f", concact_val, index))
# # A tibble: 3 x 3
#          index concact_val result       
#          <dbl> <chr>       <chr>        
# 1 123000789000 C           C123000789000
# 2 123456000000 A           A123456000000
# 3 123000000012 B           B123000000012

如果某些index 有可能有小数部分,这将默默地舍入它们。如果这是一个问题(并且您不想四舍五入),您可以在 sprintf 中使用 floor(index)

【讨论】:

    【解决方案2】:

    我们可以使用gmp中的as.bigz

    paste0(concact_val, gmp::as.bigz(index))
    [1] "C123000789000" "A123456000000" "B123000000012"
    

    或者另一种选择是在options 中指定scipen 以避免转换为科学格式

    options(scipen = 999)
    

    【讨论】:

      【解决方案3】:

      除了sprintfgmp 解决方案之外,我们还可以尝试以下其他选项作为编程实践

      f <- function(x) {
        res <- c()
        while (x) {
          res <- append(res, x %% 10)
          x <- x %/% 10
        }
        paste0(rev(res), collapse = "")
      }
      paste0(concact_val, Vectorize(f)(index))
      # [1] "C123000789000" "A123456000000" "B123000000012"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        相关资源
        最近更新 更多