用R中的gsub删除尾随空格 [英] removing trailing spaces with gsub in R

查看:101
本文介绍了用R中的gsub删除尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人用gsub删除变量尾部空格吗?

Does anyone have a trick to remove trailing spaces on variables with gsub?

以下是我的数据示例.如您所见,变量中同时包含尾随空格和空格.

Below is a sample of my data. As you can see, I have both trailing spaces and spaces embedded in the variable.

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

我可以使用以下逻辑删除所有空格,但我真正想要的是仅在结尾处移动空格.

I can use the following logic to remove all spaces, but what I really want is to only move the spaces at the end.

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

任何帮助将不胜感激.

推荐答案

您可以使用正则表达式:

You could use an regular expression:

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

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

$ stand for the end of your text sequence, therefore only trailing spaces are matched. perl=T enables regular expressions for the match pattern. For more on regular expression see ?regex.

这篇关于用R中的gsub删除尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆