Remove All White Space from Character String in R
In this article, we are going to see how to remove all the white space from character string in R Programming Language.
We can do it in these ways:
- Using gsub() function.
- Using str_replace_all() function.
Method 1: Using gsub() Function
gsub() function is used to remove the space by removing the space in the given string.
Syntax: gsub(” “, “”, input_string)
where
- First parameter takes the space to check the string has space
- Second parameter replaces with “No space” if there is space in the string
- Third parameter is the input string.
Example: R program to remove white space from character string using gsub() function.
R
# consider the string data = "Hello Geek welocme to Geeksforgeeks" print ( "Original String:" ) print (data) print ( "After remove white space:" ) # remove white spaces print ( gsub ( " " , "" ,data)) |
Output:
[1] "Original String:" [1] "Hello Geek welocme to Geeksforgeeks" [1] "After remove white space:" [1] "HelloGeekwelocmetoGeeksforgeeks"
Method 2 : Using str_replace_all() function
This function is used to replace white space with empty, It is similar to gsub() function. It is available in stringr package. To install this module type the below command in the terminal.
install.packages("stringr")
Here we use str_replace_all() function to remove white space in a string.
Syntax: str_replace_all(input_string,” “, “”)
where
- First parameter takes the input string
- Second parameter replaces with “No space” if there is space in the string
- Third parameter is to check the string has space
Example: R program to remove white space in the character string
R
# consider the string string= "Hello Geek welocme to Geeksforgeeks" print ( "Original String:" ) print (string) print ( "After remove white space:" ) # remove white spaces print ( str_replace_all (string, " " , "" )) |
Output:
[1] "Original String:" [1] "Hello Geek welocme to Geeksforgeeks" [1] "After remove white space:" [1] "HelloGeekwelocmetoGeeksforgeeks"
Please Login to comment...