【问题标题】:How to concatenate numbers with padding in R?如何在R中将数字与填充连接起来?
【发布时间】:2019-01-29 13:13:58
【问题描述】:

我有这个由 8 个一位或两位数的整数变量组成的数据集,我想将它们连接起来,但在开头用 0 填充 1 位数字。

例如,图像上的第一个示例将变为“1215020401010102”。

我不想要完整的代码解决方案,只需要哪些功能可以帮助我。我一直在尝试制作一个与 sapply 一起使用的函数,但没有成功。

【问题讨论】:

  • 看来您基本上是在使用这些作为文本值并可能粘贴它们......对吗?或者你将它们乘以 10 的适当幂? x1 * 10^14 + x2* 10^12等....也请不要粘贴数据图像,做一个小数据集,有人可以复制和粘贴。

标签: r concatenation concat


【解决方案1】:

鉴于此数据

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.callpaste0lapplyformatC

do.call(paste0, lapply(dat, formatC, width = 2, flag = "0"))
# [1] "030903" "041002" "060707" "100704" "030108"

【讨论】:

    【解决方案2】:

    这是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))
    

    【讨论】:

      猜你喜欢
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多