消除空白

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)和空格。