如何在 R 中将数字与填充连接起来?
How to concatenate numbers with padding in R?
我有一个包含 8 个一位或两位整数变量的数据集,我想将它们连接起来,但是用 1 位数字和开头的 0 填充数字。
例如,图像上的第一个示例将变为“1215020401010102”。
我不想要完整的代码解决方案,只是什么功能可以帮助我。我一直在尝试制作一个与 sapply 一起使用的功能,但一直没有成功。
鉴于此数据
set.seed(1)
(dat <- as.data.frame(matrix(sample(10, 15, T), nrow = 5)))
# V1 V2 V3
#1 3 9 3
#2 4 10 2
#3 6 7 7
#4 10 7 4
#5 3 1 8
我们可以在这里使用 do.call
和 paste0
以及 lapply
和 formatC
:
do.call(paste0, lapply(dat, formatC, width = 2, flag = "0"))
# [1] "030903" "041002" "060707" "100704" "030108"
这里有一个选项sprintf
do.call(sprintf, c(dat, fmt = "%02d%02d%02d"))
#[1] "030903" "041002" "060707" "100704" "030108"
或使用tidyverse
library(tidyverse)
dat %>%
mutate_all(str_pad, pad = '0', width = 2) %>%
unite(V1, V1, V2, V3, sep='')
# or if there are many columns use
# unite(V1, !!! rlang::syms(names(.)), sep='')
数据
dat <- structure(list(V1 = c(3L, 4L, 6L, 10L, 3L), V2 = c(9L, 10L, 7L,
7L, 1L), V3 = c(3L, 2L, 7L, 4L, 8L)), class = "data.frame", row.names = c(NA,
-5L))
我有一个包含 8 个一位或两位整数变量的数据集,我想将它们连接起来,但是用 1 位数字和开头的 0 填充数字。
例如,图像上的第一个示例将变为“1215020401010102”。
我不想要完整的代码解决方案,只是什么功能可以帮助我。我一直在尝试制作一个与 sapply 一起使用的功能,但一直没有成功。
鉴于此数据
set.seed(1)
(dat <- as.data.frame(matrix(sample(10, 15, T), nrow = 5)))
# V1 V2 V3
#1 3 9 3
#2 4 10 2
#3 6 7 7
#4 10 7 4
#5 3 1 8
我们可以在这里使用 do.call
和 paste0
以及 lapply
和 formatC
:
do.call(paste0, lapply(dat, formatC, width = 2, flag = "0"))
# [1] "030903" "041002" "060707" "100704" "030108"
这里有一个选项sprintf
do.call(sprintf, c(dat, fmt = "%02d%02d%02d"))
#[1] "030903" "041002" "060707" "100704" "030108"
或使用tidyverse
library(tidyverse)
dat %>%
mutate_all(str_pad, pad = '0', width = 2) %>%
unite(V1, V1, V2, V3, sep='')
# or if there are many columns use
# unite(V1, !!! rlang::syms(names(.)), sep='')
数据
dat <- structure(list(V1 = c(3L, 4L, 6L, 10L, 3L), V2 = c(9L, 10L, 7L,
7L, 1L), V3 = c(3L, 2L, 7L, 4L, 8L)), class = "data.frame", row.names = c(NA,
-5L))