8

有没有人有办法用 gsub 删除变量上的尾随空格?

以下是我的数据示例。如您所见,我在变量中嵌入了尾随空格和空格。

county <- c("mississippi ","mississippi canyon","missoula ",
            "mitchell ","mobile ", "mobile bay")  

我可以使用以下逻辑删除所有空格,但我真正想要的是只在最后移动空格。

county2 <- gsub(" ","",county)

任何帮助将不胜感激。

4

4 回答 4

32

阅读?regex以了解正则表达式的工作原理。

gsub("[[:space:]]*$","",county)

[:space:]是一个预定义的字符类,与您的语言环境中的空格字符匹配。 *表示重复匹配零次或多次,并$表示匹配字符串的结尾。

于 2012-05-08T16:47:06.037 回答
13

您可以使用正则表达式:

 county <- c("mississippi ","mississippi canyon","missoula ",
        "mitchell ","mobile ", "mobile bay")  
 county2 <- gsub(" $","", county, perl=T)

$代表文本序列的结尾,因此只匹配尾随空格。perl=T为匹配模式启用正则表达式。有关正则表达式的更多信息,请参阅?regex

于 2012-05-08T16:46:32.110 回答
8

如果您不需要使用 gsub 命令 - str_trim 函数对此很有用。

    library(stringr)
    county <- c("mississippi ","mississippi canyon","missoula ",
        "mitchell ","mobile ", "mobile bay")
    str_trim(county)
于 2013-08-09T18:15:22.637 回答
0
Above solution can not be generalized. Here is an example:


    a<-" keep business moving"
    str_trim(a) #Does remove trailing space in a single line string

However str_trim() from 'stringr' package works only for a vector of words   and a single line but does not work for multiple lines based on my testing as consistent with source code reference. 

    gsub("[[:space:]]*$","",a) #Does not remove trailing space in my example
    gsub(" $","", a, perl=T) #Does not remove trailing space in my example

Below code works for both term vectors and or multi-line character vectors   which was provided by the reference[1] below. 

    gsub("^ *|(?<= ) | *$", "", a, perl=T)


#Reference::
于 2016-01-09T02:16:50.557 回答