Home > database >  how to remove the initial 0 from a middle character in r
how to remove the initial 0 from a middle character in r

Time:12-14

I am trying to remove the leading zeros from a column that contains some addresses:

address_data <- data.frame(current_address = c("1470 W 2055 S", "360 N 0390 E","1076 S 0600 E"),
                           expected_address = c("1470 W 2055 S", "360 N 390 E", "1076 S 600 E"))

CodePudding user response:

# Data Input ----
address_data <- data.frame(current_address = c("1470 W 2055 S", "0360 N 0390 E","1076 S 0600 E"))
address_data
#>   current_address
#> 1   1470 W 2055 S
#> 2   0360 N 0390 E
#> 3   1076 S 0600 E

# Base R Solution
address_data$expected_address <- gsub("^0 | 0 ", " ", address_data$current_address)

## Output 1
address_data
#>   current_address expected_address
#> 1   1470 W 2055 S    1470 W 2055 S
#> 2   0360 N 0390 E      360 N 390 E
#> 3   1076 S 0600 E     1076 S 600 E

# Tidyverse Solution
library(dplyr)
library(stringr)

address_data <- address_data  %>%
  mutate(expected_address_tidyverse = str_replace_all(current_address, "^0 | 0 ", " "))

## Output 2
address_data
#>   current_address expected_address expected_address_tidyverse
#> 1   1470 W 2055 S    1470 W 2055 S              1470 W 2055 S
#> 2   0360 N 0390 E      360 N 390 E                360 N 390 E
#> 3   1076 S 0600 E     1076 S 600 E               1076 S 600 E

Created on 2022-12-13 with reprex v2.0.2

CodePudding user response:

address_data <- data.frame(current_address = c("1470 W 2055 S", "360 N 0390 E","1076 S 0600 E"))
dplyr::mutate(address_data, expected_address= gsub("^0| 0"," ",current_address))
  • Related