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

时间:2017-08-13 13:36:41

标签: r string dataframe converter

我在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

2 个答案:

答案 0 :(得分:1)

我们可以使用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

答案 1 :(得分:1)

借用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))