How can I trim leading and trailing white space?

后端 未结 13 1787
北海茫月
北海茫月 2020-11-22 03:53

I am having some troubles with leading and trailing white space in a data.frame.

For example, I like to take a look at a specific row in a data.fra

13条回答
  •  礼貌的吻别
    2020-11-22 04:19

    I created a trim.strings () function to trim leading and/or trailing whitespace as:

    # 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)
        } 
    } 
    

    For illustration,

    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"   
    

提交回复
热议问题