2

Ultimately I want to convert this value into as.numeric but before this I want to replace space for zeros. I do 2 step sub here as I can do only single space at the time. Can do this in one command?

x <- c('  3','1 2','12 ')    ## could be leading, trailing or in the mid
x
as.numeric(x)      ## <@><<    NAs introduced by coercion
x <- sub(' ','0',sub(' ','0',x))
as.numeric(x)
Mike S
  • 296
  • 2
  • 14
  • What is the point of adding leading zeroes to a whole number? – Tim Biegeleisen Jun 15 '17 at 14:23
  • 4
    What's wrong with just `as.numeric(x)`? (FYI `sub('\\s+', '00', x)`) – Sotos Jun 15 '17 at 14:24
  • 1
    yes, just do as.numeric(x), to remove all spaces do `gsub('\\s', '', x)`. What Sotos gave will replace with zeroes the first sequence of zeros that is encountered (it won't for example replace spaces that would be after the first non empty characters if x <- ' 3 ' – moodymudskipper Jun 15 '17 at 14:40
  • 1
    Use formatting options (see [here](https://stackoverflow.com/questions/5812493/adding-leading-zeros-using-r)): `x <- 25499` `sprintf("%06d", x)` `[1] "025499"` – Alex Knorre Jun 15 '17 at 14:55
  • 1
    Thanks guys all, I don't want to break alignment as it's pretty complex structure, it's logical 0,1,2,3s and I refer to my value by substring(x,120,122), + I need to keep it for audit. So Ideally I would like just to replace blanks with zeros. I modified my sample to be more real, so as.numeric will break on it. For other calcs it will work as suggested by all you . Tx M – Mike S Jun 15 '17 at 17:10

1 Answers1

1

This approach can replace all leading white space to leading 0.

# Load package
library(stringr)

# Create example strings with leading white space and number
x <- c("  3", "    4", "    12")

x %>%
  # Trim the leading white space
  str_trim(side = "left") %>%
  # Add leading 0, the length is based on the original stringlength
  str_pad(width = str_length(x), side = "left", pad = "0")

#[1] "003"    "00004"  "000012"

Update

My previous attempt is actually convoluted. Using gsub can achieve the same thing with only one line.

gsub(" ", "0", x)
#[1] "003"    "00004"  "000012"

And it does not have to be leading white space. Taking the update from the OP as an example.

x <- c('  3','1 2','12 ')
gsub(" ", "0", x)
#[1] "003" "102" "120"
www
  • 38,575
  • 12
  • 48
  • 84