首页 文章

如何修剪前导和尾随空格?

提问于
浏览
313

我在data.frame中遇到了前导和尾随空格的麻烦 . 例如,我想基于某个条件查看 data.frame 中的特定 row

> myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)] 

[1] codeHelper     country        dummyLI    dummyLMI       dummyUMI       
[6] dummyHInonOECD dummyHIOECD    dummyOECD      
<0 rows> (or 0-length row.names)

我想知道为什么我没有得到预期的输出,因为奥地利显然存在于我的 data.frame . 在查看我的代码历史记录并试图弄清楚出了什么问题后,我尝试了:

> myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)]
   codeHelper  country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD
18        AUT Austria        0        0        0              0           1
   dummyOECD
18         1

我在命令中改变的是奥地利之后的另外一个空格 .

显然会出现更烦人的问题 . 例如,当我想根据国家/地区列合并两个帧时 . 一个 data.frame 使用 "Austria " 而另一个框架具有 "Austria" . 匹配不起作用 .

  • 是否有一个很好的方法'show'我的屏幕上的空白,以便我知道这个问题?

  • 我可以删除R中的前导和尾随空格吗?

到目前为止,我曾经写过一个简单的 Perl 脚本来删除空格,但如果我可以在R里面以某种方式做到这一点会很好 .

13 回答

  • 462

    最好的方法是trimws()

    以下代码将此函数应用于整个数据帧

    mydataframe < - data.frame(lapply(mydataframe,trimws),stringsAsFactors = FALSE)

  • 4

    可能最好的方法是在读取数据文件时处理尾随空格 . 如果使用 read.csvread.table ,则可以设置参数 strip.white=TRUE .

    如果您想在之后清理字符串,可以使用以下函数之一:

    # returns string w/o leading whitespace
    trim.leading <- function (x)  sub("^\\s+", "", x)
    
    # returns string w/o trailing whitespace
    trim.trailing <- function (x) sub("\\s+$", "", x)
    
    # returns string w/o leading or trailing whitespace
    trim <- function (x) gsub("^\\s+|\\s+$", "", x)
    

    要在 myDummy$country 上使用以下功能之一:

    myDummy$country <- trim(myDummy$country)
    

    要“显示”您可以使用的空白:

    paste(myDummy$country)
    

    它将显示由引号(“)包围的字符串,使空格更容易被发现 .

  • 10

    从R 3.2.0开始,引入了一个用于删除前导/尾随空格的新函数:

    trimws()
    

    见:http://stat.ethz.ch/R-manual/R-patched/library/base/html/trimws.html

  • 8

    要操作空格,请在stringr包中使用str_trim() . 该软件包的手册日期为2013年2月15日,并且在CRAN中 . 该函数还可以处理字符串向量 .

    install.packages("stringr", dependencies=TRUE)
    require(stringr)
    example(str_trim)
    d4$clean2<-str_trim(d4$V2)
    

    (学分归于评论者:R . Cotton)

  • 22

    一个简单的 function 删除前导和尾随空格:

    trim <- function( x ) {
      gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
    }
    

    Usage:

    > text = "   foo bar  baz 3 "
    > trim(text)
    [1] "foo bar  baz 3"
    
  • 5

    ad1)要查看空格,您可以使用修改后的参数直接调用 print.data.frame

    print(head(iris), quote=TRUE)
    #   Sepal.Length Sepal.Width Petal.Length Petal.Width  Species
    # 1        "5.1"       "3.5"        "1.4"       "0.2" "setosa"
    # 2        "4.9"       "3.0"        "1.4"       "0.2" "setosa"
    # 3        "4.7"       "3.2"        "1.3"       "0.2" "setosa"
    # 4        "4.6"       "3.1"        "1.5"       "0.2" "setosa"
    # 5        "5.0"       "3.6"        "1.4"       "0.2" "setosa"
    # 6        "5.4"       "3.9"        "1.7"       "0.4" "setosa"
    

    有关其他选项,另请参见 ?print.data.frame .

  • 414

    使用grep或grepl查找具有空格和子的观察值以消除它们 .

    names<-c("Ganga Din\t","Shyam Lal","Bulbul ")
    grep("[[:space:]]+$",names)
    [1] 1 3
    grepl("[[:space:]]+$",names)
    [1]  TRUE FALSE  TRUE
    sub("[[:space:]]+$","",names)
    [1] "Ganga Din" "Shyam Lal" "Bulbul"
    
  • 5

    我更愿意将答案添加为对用户56的评论,但却无法写作独立答案 . 删除前导和尾随空白也可以通过gdata包中的trim()函数来实现:

    require(gdata)
    example(trim)
    

    用法示例:

    > trim("   Remove leading and trailing blanks    ")
    [1] "Remove leading and trailing blanks"
    
  • 1

    另一种选择是使用 stringi 包中的 stri_trim 函数,该函数默认删除前导和尾随空格:

    > x <- c("  leading space","trailing space   ")
    > stri_trim(x)
    [1] "leading space"  "trailing space"
    

    要仅删除前导空格,请使用 stri_trim_left . 要仅删除尾随空格,请使用 stri_trim_right . 如果要删除其他前导或尾随字符,则必须使用 pattern = 指定 .

    有关详细信息,另请参阅 ?stri_trim .

  • 0

    如果输入之间有多个空格,则会出现另一个相关问题:

    > a <- "  a string         with lots   of starting, inter   mediate and trailing   whitespace     "
    

    然后,您可以使用正则表达式轻松地将此字符串拆分为"real"标记到 split 参数:

    > strsplit(a, split=" +")
    [[1]]
     [1] ""           "a"          "string"     "with"       "lots"      
     [6] "of"         "starting,"  "inter"      "mediate"    "and"       
    [11] "trailing"   "whitespace"
    

    请注意,如果在(非空)字符串的开头存在匹配项,则输出的第一个元素为“”“,但如果字符串末尾存在匹配项,则输出结果与随着比赛被删除 .

  • 1

    我创建了一个 trim.strings () 函数来修剪前导和/或尾随空格,如下所示:

    # Arguments:    x - character vector
    #            side - side(s) on which to remove whitespace 
    #                   default : "both"
    #                   possible values: c("both", "leading", "trailing")
    
    trim.strings <- function(x, side = "both") { 
        if (is.na(match(side, c("both", "leading", "trailing")))) { 
          side <- "both" 
          } 
        if (side == "leading") { 
          sub("^\\s+", "", x)
          } else {
            if (side == "trailing") {
              sub("\\s+$", "", x)
        } else gsub("^\\s+|\\s+$", "", x)
        } 
    }
    

    为了说明,

    a <- c("   ABC123 456    ", " ABC123DEF          ")
    
    # returns string without leading and trailing whitespace
    trim.strings(a)
    # [1] "ABC123 456" "ABC123DEF" 
    
    # returns string without leading whitespace
    trim.strings(a, side = "leading")
    # [1] "ABC123 456    "      "ABC123DEF          "
    
    # returns string without trailing whitespace
    trim.strings(a, side = "trailing")
    # [1] "   ABC123 456" " ABC123DEF"
    
  • 0
    myDummy[myDummy$country == "Austria "] <- "Austria"
    

    在此之后,你需要强制R不要将“奥地利”识别为一个级别 . 让我们假装你也有“美国”和“西班牙”作为等级:

    myDummy$country = factor(myDummy$country, levels=c("Austria", "USA", "Spain"))
    

    比最高投票反应少一点恐吓,但它应该仍然有效 .

  • 81

    我试过trim() . 适用于空白区域和'\ n' . x ='\ n哈登,J . \ n'

    修剪(x)的

相关问题