For example if I have
ID rout
1 1 0123
2 2 0245
3 3 0789
4 4 0963
5 5 6779
6 6 056
7 7 zxc
8 8 asd
9 9 1234
I wonder how I can remove only the first digit of the rout
column for observations with 4 characters and only when it (the first character) is zero, and create a column (rout2
) like below:
ID rout rout2
1 1 0123 123
2 2 0245 245
3 3 0789 789
4 4 0963 963
5 5 6779 6779
6 6 056 056
7 7 zxc zxc
8 8 asd asd
9 9 1234 1234
In order to remove only the first digit when it is zero, and only for 4-digit alphanumeric values, you can do
data$rout2 <- ifelse(nchar(data$rout) == 4, sub("^[0]", "", data$rout), data$rout)
Output
# ID rout rout2
# 1 1 0123 123
# 2 2 0245 245
# 3 3 0789 789
# 4 4 0963 963
# 5 5 6779 6779
# 6 6 056 056
# 7 7 zxc zxc
# 8 8 asd asd
# 9 9 1234 1234