I have a numeric column and I would like to add the digit 0 before the last 4 digits. The columns contain numeric values, but the values have different number of digits, some have 6 digits and some have 7. So counting the numbers from the beggining will be wrong, it has to be prior to the last for digits. So, for example:
Suppose I have a column, some numbers are:
123456
1234567
I would like the result to look like this, so 0 is always the number before the last 4 digits:
1203456
12304567
I don't know if it makes sense, let me know if you need more clarification.
CodePudding user response:
We may use capture ()
the last four digits (\\d{4}
) by adding the $
to specify the end of the string and replace with the 0
followed by the backreference (\\1
) of the captured group
df1$col1 <- as.numeric(sub('(\\d{4})$', '0\\1', df1$col1))
-output
df1$col1
[1] 1203456 12304567
data
df1 <- structure(list(col1 = c(123456, 1234567)),
class = "data.frame", row.names = c(NA,
-2L))