用单个/多个零替换单个或多个空格

时间:2017-06-15 14:21:38

标签: r

最终我想将此值转换为as.numeric但在此之前我想将空格替换为零。我在这里做了两步sub,因为我当时只能做一个空格。可以在一个命令中执行此操作吗?

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)

1 个答案:

答案 0 :(得分:1)

此方法可以将所有前导空格替换为前导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"

更新

我以前的尝试实际上是错综复杂的。使用gsub可以只用一行来实现同样的目的。

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

它不一定要领先白色空间。以OP的更新为例。

x <- c('  3','1 2','12 ')
gsub(" ", "0", x)
#[1] "003" "102" "120"