# Removing zeros to the right and adding some to the left of the number?

Suppose I have the following vector

``````test<- c(374500, 2270400)
```

```

First, I want to remove the zeros to get something like:

``````test2<- c(3745, 22704)
```

```

Then I want to add zeros to the left to have 6 digits. This part I know how to do it:

``````test3 <- formatC(test2, width = 6, format = "d", flag = "0")
```

```

Can you help me with the first step?

+3

source to share

You can use regular expressions:

``````as.integer(sub("0*\$", "", test))
#   3745 22704
```

```

Also, you will find interesting recursion here:

``````remove_zeroes <- function(x) {
x <- as.integer(x)
i <- x %% 10L == 0
if (any(i)) {
x[i] <- x[i] / 10L
Recall(x)
} else x
}
remove_zeroes(c(123, 1230, 1230000))
#  123 123 123
```

```

Landmarks:

``````test <- sample.int(1e5)
library(microbenchmark)
microbenchmark(
as.integer(sub("0*\$", "", test)),
as.integer(sub("0+\$", "", test)),
remove_zeroes(test))
# Unit: milliseconds
#                              expr       min        lq    median        uq       max neval
#  as.integer(sub("0*\$", "", test)) 134.51669 138.91855 141.28812 145.96486 170.93705   100
#  as.integer(sub("0+\$", "", test)) 113.91206 118.83564 123.42199 126.44162 179.03642   100
#               remove_zeroes(test)  38.01125  47.45385  49.79928  54.87592  89.05354   100
```

```
+7

source

Later to the contributor, but here's the qdap approach:

``````test<- c(374500, 2270400)

library(qdap)

##  "003745" "022704"
```

```
+1

source

All Articles