有没有人可以使用gsub删除变量上的尾随空格?
以下是我的数据示例。如您所见,我在变量中嵌入了尾随空格和空格。
county <- c("mississippi ","mississippi canyon","missoula ",
"mitchell ","mobile ", "mobile bay")
我可以使用以下逻辑删除所有空格,但我真正想要的只是在末尾移动空格。
county2 <- gsub(" ","",county)
非常感谢任何协助。
答案 0 :(得分:31)
阅读?regex
以了解正则表达式的工作原理。
gsub("[[:space:]]*$","",county)
[:space:]
是一个预定义的字符类,它匹配您的语言环境中的空格字符。 *
表示要重复匹配零次或多次,$
表示匹配字符串的结尾。
答案 1 :(得分:12)
您可以使用正则表达式:
county <- c("mississippi ","mississippi canyon","missoula ",
"mitchell ","mobile ", "mobile bay")
county2 <- gsub(" $","", county, perl=T)
$
代表文本序列的结尾,因此只匹配尾随空格。 perl=T
为匹配模式启用正则表达式。
有关正则表达式的更多信息,请参阅?regex
。
答案 2 :(得分:8)
如果您不需要使用gsub命令 - str_trim函数对此很有用。
library(stringr)
county <- c("mississippi ","mississippi canyon","missoula ",
"mitchell ","mobile ", "mobile bay")
str_trim(county)
答案 3 :(得分: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::