Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim leading and trailing white space?

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

For example, I look at a specific row in a data.frame based on a certain condition:

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

I was wondering why I didn't get the expected output since the country Austria obviously existed in my data.frame. After looking through my code history and trying to figure out what went wrong I tried:

> 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 

All I have changed in the command is an additional white space after Austria.

Further annoying problems obviously arise. For example, when I like to merge two frames based on the country column. One data.frame uses "Austria " while the other frame has "Austria". The matching doesn't work.

  1. Is there a nice way to 'show' the white space on my screen so that I am aware of the problem?
  2. And can I remove the leading and trailing white space in R?

So far I used to write a simple Perl script which removes the whites pace, but it would be nice if I can somehow do it inside R.

like image 749
mropa Avatar asked Feb 14 '10 12:02

mropa


People also ask

How do you get rid of trailing white space?

Type M-x delete-trailing-whitespace to delete all trailing whitespace. This command deletes all extra spaces at the end of each line in the buffer, and all empty lines at the end of the buffer; to ignore the latter, change the variable delete-trailing-lines to nil .

Does trim remove leading and trailing spaces?

TRIM function - remove extra spaces in Excel You use the TRIM function in Excel removes extra spaces from text. It deletes all leading, trailing and in-between spaces except for a single space character between words.

Which method is used to remove leading and trailing?

Use the Trim() method to remove leading and trailing whitespace from a string.

What function is used to remove leading and trailing spaces?

The Trim function The most obvious (and generally efficient) method for removing both leading and trailing space is to use the TRIM() function.


1 Answers

As of R 3.2.0 a new function was introduced for removing leading/trailing white spaces:

trimws() 

See: Remove Leading/Trailing Whitespace

like image 199
wligtenberg Avatar answered Sep 18 '22 12:09

wligtenberg