Remove whitespace from strings in base R


The problem:

There are situations in R when a string character contains a white space (whitespace) that needs to be removed for further analysis. The situations below are the most common that I see in my work. (copy and paste from this webpage will not work. To follow the tutorial, use the RData file here: https://github.com/thelostphd/Examples/blob/main/stringExample.RData).

The three examples look like this (recommend downloading and importing the RData file from the above hyperlink).

ExampleString
134. 765
29.
2
4\t3
3488\u00A0. 3398

For each of the examples above, the number should be a numeric value, however R interprets them as a character because of the space characters. We will need to use regular expressions and their R functions in this tutorial. Since regular expressions will not be described on this page, I recommend the reader search the internet for an introductory background.

Base R (no additional packages) will be used for this tutorial. While there are several helpful packages to deal with strings in R, for this particular task, those packages are not necessary. This also introduces some of the functionality available in base R.

While our goal is to convert these to numeric, the same logic applies with other strings. Obviously, for one-off values we can fix them and move on with our analysis. However, our goal will be to evaluate a larger character vector and at the end of this tutorial, we will see how to create a function within R to remove spaces.

First we will load the RData file with the following line of code (unless your name is Matthew, make sure the path uses your download file). The ‘stringExample’ variable is a simple data frame with one column and three rows.

load("C:/Users/Matthew/Downloads/stringExample.RData")

Example 1: A simple space of white space

The first example is only a space created by a space bar. The following code evaluates the variable, stringExample and attempts to convert it to numeric using the as.numeric() function. An error is thrown and the result is NA. We see that the class is “character”, so the variable needs cleaning before it can be converted.

stringExample
            String
1          34. 765
2 9. \n2\n4\t\t3\n
3       488 . 3398

stringExample[1, ]
[1] "34. 765"

as.numeric(stringExample[1, ])
[1] NA
Warning message:
NAs introduced by coercion

class(stringExample[1, ])
[1] "character"

Now we can use the gsub() function to eliminate the space. The gsub() function requires at least three inputs (see the documentation for some other inputs), gsub(pattern, replacement, x). For the space, we will use:

  • pattern = “[ ]”
    • The pattern must be in quotes since it is a string, and is a regular expression
    • Between the brackets, a single space is inserted
    • The brackets essentially tell the function to look through the entire string for spaces
    • Some people recommend “[[:blank:]]” for spaces and tabs, although I haven’t used it in favor of alternatives
    • If ” ” is used (a single space between double quotes), it would only work when x = ” “. Try the code below.
fun_example <- " "
gsub(" ", "hi", fun_example)
  • replacement = “”
    • The replacement is what the function will substitute in when it the pattern is found
    • Since we are eliminating a space, we use empty double quotes
    • If you knew that the space was an error and a number should be in it’s place, then you could insert that number within the double quotes
  • x = example_1_raw
    • This is the variable that will be evaluated for the pattern

After the gsub() function and creation of the example_1 variable, the result is converted to numeric, without error. As a check, the class of example_1 is executed and the result is indeed, numeric.

(example_1 <- gsub("[ ]", "", stringExample[1, ]))
[1] "34.765"

(example_1 <- as.numeric(example_1))
[1] 34.765

class(example_1)
[1] "numeric"

Note, in the above code, placing the line of code within parentheses tells R to output the result to the console.

Example 2: Multiple types of whitespace

Whitespace can be caused by other characters than spaces from a space bar. For example, this example includes carriage returns and tabs. Below we execute the second row of the stringExample variable. As seen, there are two regular expressions, “\n” and “\t” a carriage return and tab, respectively.

stringExample[2, ]
[1] "9. \n2\n4\t\t3\n"

Next, we will show the progression of whitespace elimination. The first line is the same as in Example 1 and only removes the space after the “9.”. The second line uses the “[[:blank:]]” expression to remove the space and the tab. And the third line removes all the white space with the “[[:space:]]” expression. The last light converts the last variable to numeric.

(example_2a <- gsub("[ ]", "", stringExample[2, ]))
[1] "9.\n2\n4\t\t3\n"

(example_2b <- gsub("[[:blank:]]", "", stringExample[2, ]))
[1] "9.\n2\n43\n"

(example_2c <- gsub("[[:space:]]", "", stringExample[2, ]))
[1] "9.243"

(example_2 <- as.numeric(example_2c))
[1] 9.243

The “[[:blank:]]” and “[[:space:]]” expressions are unique to R. As described above, the “[[:blank:]]” expression can be used for spaces and tabs. The “[[:space:]]” expression is fairly universal and removes almost all whitespace characters.

My go-to expression is “[[:space:]]” to avoid any hidden unicode. However, it does not remove what we find in the third example.

Example 3: Unicode u00A0, a ‘no-break space’ whitespace

Since this one has been a particular challenge for me, it deserves its own example. Output from a Power Automate Desktop RPA (robotic process automation) website extraction gave me this space. Thankfully I found a hint in this Stacked Overflow post that mentioned this whitespace.

In the code, below, the \u00A0 unicode is written into the string, but once the variable is evaluated, it looks like a simple space. To complicate the issue, additional space characters are included.

stringExample[3, ]
[1] "488   . 3398"

As in example 2, we proceed step by step to remove the whitespace. Notice in examples 3a, 3b and 3c, the space after the decimal place is removed, while the space preceding the decimal place is unaffected. In example 3d, the decimal place moves to the left, however there are still multiple spaces.

(example_3a <- gsub("[ ]", "", stringExample[3, ]))
[1] "488  .3398"

(example_3b <- gsub("[[:blank:]]", "", stringExample[3, ]))
[1] "488  .3398"

(example_3c <- gsub("[[:space:]]", "", stringExample[3, ]))
[1] "488  .3398"

(example_3d <- gsub("\u00A0", "", stringExample[3, ]))
[1] "488 . 3398"

In the next block of code, the gsub() function is used twice, first to remove the u00A0 unicode character, then to remove any remaining whitespace. And then a check follows to convert example_3e to numeric and it’s successful.

(example_3e <- gsub("[[:space:]]", "", gsub("\u00A0", "", stringExample[3, ])))
[1] "488.3398"

(example_3 <- as.numeric(example_3e))
[1] 488.3398

While we worked through each string separately, the entire data.frame can be converted to numeric with one line of code. Because the input was a dataframe, we will return a data.frame. The unlist() function splits out the data.frame, otherwise the gsub function was evaluating all the values together, rather than individually.

(example_final <- data.frame(String = as.numeric(gsub("[[:space:]]", "", gsub("\u00A0", "", unlist(stringExample))))))
    String
1  34.7650
2   9.2430
3 488.3398

Summary

This was a short demonstration to remove whitespace from strings. While the examples were all converted to numeric at the end, these same principles apply any time whitespace needs to be removed from character strings.


Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish