将最后两位数改为" 00"

时间:2017-10-12 05:53:22

标签: r

假设我有以下data.frame:

dt=data.frame(id=LETTERS[1:5],code=c("101011,101102,101130","211011,101102",
  "101011,301102,101132","201015,401102,103412","131011,101101,105430"))

id                   code
A    101011,101102,101130
B           211011,101102
C    101011,301102,101132
D    201015,401102,103412
E    131011,101101,105430
F           101100,103200`

我希望最后两个代码数字成为" 00",就像这样:

id                   code
A    101000,101100,101100
B           211000,101100
C    101000,301100,101100
D    201000,401100,103400
E    131000,101100,105400
F           101100,103200`

我该怎么做?

1 个答案:

答案 0 :(得分:3)

gsub使用\\d{2}\\b; \\b与单词边界匹配的地方,\\d{2}\\b因此匹配单词边界之前的两位数字;使用gsub将所有匹配替换为00

dt$code <- gsub('\\d{2}\\b', '00', dt$code)

dt
#  id                 code
#1  A 101000,101100,101100
#2  B        211000,101100
#3  C 101000,301100,101100
#4  D 201000,401100,103400
#5  E 131000,101100,105400