如何删除前导空格

时间:2014-09-17 21:17:12

标签: r gsub

我对R中的文本处理并不熟悉,并坚持如何删除字符串中的前导空格。这是一些代码:

set.seed(1234)
b <- paste0(sample(c("bbb ", " bbb "), 10, replace = TRUE), rep("ccc ddd", 10))
print(b)

 [1] "bbb ccc ddd"  " bbb ccc ddd" " bbb ccc ddd" " bbb ccc ddd" " bbb ccc ddd"
 [6] " bbb ccc ddd" "bbb ccc ddd"  "bbb ccc ddd"  " bbb ccc ddd" " bbb ccc ddd"

我发现我可以删除尾随空格sub(' +$', '', b),但将其更改为子('$+ ', '', b)不会删除前导空格。猜猜这是一个快速解决方案......

2 个答案:

答案 0 :(得分:5)

str_trim尝试stringr

左侧

> library(stringr)
> str_trim(b, "left")
# [1] "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd"
# [6] "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd"

同样,str_trim(b, "right")为右侧。对于双方来说,只需str_trim(b)

答案 1 :(得分:3)

如果你回答这个问题:

How to trim leading and trailing whitespace in R?

你会看到一个关于修剪空白的非常彻底的答案:那里的答案给出了以下功能:

trim.leading <- function (x)  sub("^\\s+", "", x)

申请数据:

set.seed(1234)
b <- paste0(sample(c("bbb ", " bbb "), 10, replace = TRUE), rep("ccc ddd", 10))
b

trim.leading(b)

#[1] "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" 
#[8] "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd" "bbb ccc ddd"