How to Delete Leading & Trailing Zeros in R (2 Examples)

This article shows how to remove one or multiple zeros at the beginning and at the end of a character string in the R programming language.

Creation of Example Data

x <- "000001234560000000"        # Example value
x                                # Show example value in RStudio console
# [1] "000001234560000000"

Example 1: Applying sub Function to Remove Leading Zeros

sub("^0+", "", x)                # Deleting leading zeros
# [1] "1234560000000"

Example 2: Applying sub Function to Remove Trailing Zeros

sub("0+$", "", x)                # Deleting trailing zeros
# [1] "00000123456"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top