R语言 粘贴具有不同分隔符的3个字符串时出错

eqfvzcg8  于 2023-01-15  发布在  其他
关注(0)|答案(4)|浏览(178)

也许这是一个废话,但我一直在玩粘贴和粘贴没有成功。
我的数据框如下所示

stck <-structure(list(haul = 1:11,
         year = c(1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L)),
         row.names = c(NA, 11L), class = "data.frame")

我试着生成这样的代码:N83_01, N83_02, ...., N83_10
也就是说,我想创建一个代码,粘贴年份的最后两个数字加上运输编号(以“两个数字”格式)。
到目前为止,我找不到粘贴“N”的方法。这是我所拥有的

stck$cod_lance <- as.factor(ifelse (stck$lance >=1 & stck$lance <10, paste(str_sub(stck$fecha, 3, 4), stck$lance, sep="_0"),
                                    paste(str_sub(stck$fecha, 3, 4), stck$lance, sep="_")))

我怎样才能得到正确的输出?。提前感谢。

pqwbnv8z

pqwbnv8z1#

使用paste0以避免分隔符。将"N"作为第一个参数传递,然后使用substrstck$year %% 100传递stck$year的最后两位数字。接下来是下划线,最后是运输编号。在使用sprintf传递单个数字时,可以在运输编号前补零:

paste0('N', substr(stck$year, 3, 4), "_", sprintf('%02d', stck$haul))
#>  [1] "N83_01" "N83_02" "N83_03" "N83_04" "N83_05" "N83_06" "N83_07"
#>  [8] "N83_08" "N83_09" "N83_10" "N83_11
6ojccjat

6ojccjat2#

您还可以将所有内容与sprintf结合使用

sprintf('N%1$d_%2$02d', stck$year %% 100, stck$haul)

# [1] "N83_01" "N83_02" "N83_03" "N83_04" "N83_05" "N83_06"
# "N83_07" "N83_08" "N83_09" "N83_10" "N83_11"
j9per5c4

j9per5c43#

当然可以使用Allan's answer,但是为了完成现有代码,我们可以添加另一个 paste 作为前缀N

library(stringr)

as.factor(
  paste0("N",
  ifelse(stck$haul >= 1 & stck$haul < 10,
          paste(str_sub(stck$year, 3, 4), stck$haul, sep="_0"),
          paste(str_sub(stck$year, 3, 4), stck$haul, sep="_")))
  )

#  [1] N83_01 N83_02 N83_03 N83_04 N83_05 N83_06 N83_07 N83_08 N83_09 N83_10 N83_11 N83_12
# Levels: N83_01 N83_02 N83_03 N83_04 N83_05 N83_06 N83_07 N83_08 N83_09 N83_10 N83_11 N83_12
7eumitmz

7eumitmz4#

下面是使用formatC和一些tidyverse帮助器的替代方法:

library(dplyr)
library(stringr)
stck %>% 
  mutate(x = paste0("N", str_sub(year, -2), "_", formatC(haul, width=2, flag="0"))) %>% 
  pull(x)
"N83_01" "N83_02" "N83_03" "N83_04" "N83_05" "N83_06" "N83_07" "N83_08" "N83_09" "N83_10" "N83_11"

相关问题