How to use gsub() In R Language

In this approach, we have used apply() function to apply a function to each row in a data frame. The function used which is applied to each row in the dataframe is the gsub() function, this used to replace all the matches of a pattern from a string, we have used to gsub() function to find whitespace(\s), which is then replaced by “”, this removes the whitespaces.

Note: We have wrapped our entire output in as.data.frame() function, it is because the apply() function returns a Matrix object so we need to convert it back into a dataframe.

Syntax: as.data.frame(apply(df,margin, function(x) gsub(“\\s+”, “”, x)))

Parameters:

df: Dataframe object

margin: dimension on which operation is to be applied

function(x): operation to be applied, gsub() in this case.

gsub(): replaces “\s” with “”

Example: R program to remove whitespaces using gsub()

R




df <- data.frame(c1 = c("  geeks for", "  cs", "r   -lang "),
                 c2 = c("geeks ", "f ", "  g"))
 
df_new <- as.data.frame(
  apply(df,2, function(x) gsub("\\s+", "", x)))
 
df_new


Output:

        c1    c2

1 geeksfor geeks

2       cs     f

3   r-lang     g

Remove All Whitespace in Each DataFrame Column in R

In this article, we will learn how to remove all whitespace in each dataframe column in R programming language.

Sample dataframe in use:

           c1     c2
1   geeks for geeks 
2          cs     f 
3  r   -lang       g

Similar Reads

Method 1: Using gsub()

In this approach, we have used apply() function to apply a function to each row in a data frame. The function used which is applied to each row in the dataframe is the gsub() function, this used to replace all the matches of a pattern from a string, we have used to gsub() function to find whitespace(\s), which is then replaced by “”, this removes the whitespaces....

Method 2: Using str_remove_all()

...

Method 3: Using str_replace_all()

We need to first install the package “stringr” by using install.packages() command and then import it using library() function....

Contact Us