How can I trim leading and trailing white space?

后端 未结 13 1497
北海茫月
北海茫月 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:09

    Probably the best way is to handle the trailing white spaces when you read your data file. If you use read.csv or read.table you can set the parameterstrip.white=TRUE.

    If you want to clean strings afterwards you could use one of these functions:

    # Returns string without leading white space
    trim.leading <- function (x)  sub("^\\s+", "", x)
    
    # Returns string without trailing white space
    trim.trailing <- function (x) sub("\\s+$", "", x)
    
    # Returns string without leading or trailing white space
    trim <- function (x) gsub("^\\s+|\\s+$", "", x)
    

    To use one of these functions on myDummy$country:

     myDummy$country <- trim(myDummy$country)
    

    To 'show' the white space you could use:

     paste(myDummy$country)
    

    which will show you the strings surrounded by quotation marks (") making white spaces easier to spot.

提交回复
热议问题