R将double转换为字符串r而不转换为科学
R Convert double to string r without converting to scientific
有一个场景,我有一个很长的(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
)。
我们可以使用 as.bigz
来自 gmp
paste0(concact_val, gmp::as.bigz(index))
[1] "C123000789000" "A123456000000" "B123000000012"
或者另一种选择是在 options
中指定 scipen
以避免转换为科学格式
options(scipen = 999)
使用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)
除了sprintf
和gmp
的解决方案,我们可能会尝试像下面这样的另一个选项作为编程实践
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"
有一个场景,我有一个很长的(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
)。
我们可以使用 as.bigz
来自 gmp
paste0(concact_val, gmp::as.bigz(index))
[1] "C123000789000" "A123456000000" "B123000000012"
或者另一种选择是在 options
中指定 scipen
以避免转换为科学格式
options(scipen = 999)
使用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)
除了sprintf
和gmp
的解决方案,我们可能会尝试像下面这样的另一个选项作为编程实践
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"