如何在 R 的数据框中将代码 T-25-4 更改为 T-25-04?

How to change code T-25-4 into T-25-04 in a dataframe in R?

我在 R 中有一个 data.frame。第一列包含类似 T-25-4 的代码。我想把它改成T-25-04等等。所以最后一个数字应该是2位数字

示例:

T-25-1
T-25-2
T-25-3
T-25-4
T-25-5
T-25-6
T-25-7
T-25-8
T-25-9

我们可以使用 tidyversestringr 中的函数。 df2 是最终输出。

library(tidyverse)
library(stringr)

# Create example data frame
dt <- data_frame(Col = c("T-25-1", "T-25-2", "T-25-3", "T-25-4", "T-25-5",
                         "T-25-6", "T-25-7", "T-25-8", "T-25-9"))

# Process the data
dt2 <- dt %>%
  # Separate the original column to three columns
  separate(Col, into = c("Col1", "Col2", "Col3")) %>%
  # Pad zero to Col3 until the width is 2
  mutate(Col3 = str_pad(Col3, width = 2, side= "left", pad = "0")) %>%
  # Combine all three columns separated by "-
  unite(Col, Col1:Col3, sep = "-")

# View the reuslts
dt2
# A tibble: 9 x 1
      Col
*   <chr>
1 T-25-01
2 T-25-02
3 T-25-03
4 T-25-04
5 T-25-05
6 T-25-06
7 T-25-07
8 T-25-08
9 T-25-09

借用 ycw 答案的第一部分,但使用 mutategsub 更简单:

library(tidyverse)
dt <- data_frame(Col = c("T-25-1", "T-25-2", "T-25-3", "T-25-4", "T-25-5",
                     "T-25-6", "T-25-7", "T-25-8", "T-25-9"))

dt %>%
  mutate(Col = gsub("(\d)$", paste0("0", "\1"), Col))

如果最后一位数字大于 9 而您不想加 0:

dt %>%
  mutate(Col = ifelse(nchar(sub(".*-(\d+)$", "\1", Col)) < 2, # Check if last number is less than 10
                      sub("(\d+)$", paste0("0", "\1"), Col), # Add 0 in front if less than 10
                      Col))