消除空白

string <- '    some text on line one; 
and then some text on line two     '

修剪空白

修剪空格通常是指从字符串中删除前导和尾随空格。这可以使用先前示例的组合来完成。gsub 用于强制替换前导和尾随匹配。

在 R 3.2.0 之前

gsub(pattern = "(^ +| +$)",
     replacement = "",
     x = string)

[1] "some text on line one; \nand then some text on line two"

R 3.2.0 及更高

trimws(x = string)

[1] "some text on line one; \nand then some text on line two"

删除前导空格

在 R 3.2.0 之前

sub(pattern = "^ +", 
    replacement = "",
    x = string)

[1] "some text on line one; \nand then some text on line two     "

R 3.2.0 及更高

trimws(x = string,
       which = "left")

[1] "some text on line one; \nand then some text on line two     "

删除尾随空格

在 R 3.2.0 之前

sub(pattern = " +$",
    replacement = "",
    x = string)

[1] "    some text on line one; \nand then some text on line two"

R 3.2.0 及更高

trimws(x = string,
       which = "right")

[1] "    some text on line one; \nand then some text on line two"

删除所有空格

gsub(pattern = "\\s",   
     replacement = "",
     x = string)

[1] "sometextonlineone;andthensometextonlinetwo"

请注意,这也将删除空白字符,例如制表符(\t),换行符(\r\n)和空格。