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" |
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" |
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" |
sub("0+$", "", x) # Deleting trailing zeros # [1] "00000123456"