Remove Newline from Character String in R
In this article, we are going to see how to remove the new line from a character string in R Programming Language.
Input: String with newline: "Hello\nGeeks\rFor\r\n Geeks" Output: String after removing new line: "HelloGeeksFor Geeks"
Method 1: Using gsub() function
gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.
gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
pattern: string to be matched
replacement: string for replacement
string: String or String vector
ignore.case: Boolean value for case-sensitive replacement
Example: R program to remove the newline from character string using gsub() function.
Syntax: gsub(“[\r\n]”, “”, string)
- [\r\n] is a first parameter which is a pattern to remove new lines
- “” is the second parameter that replaces when new line occurs as empty
- string is the input string of characters.
 "Original string: " Hello Geeks For Geeks  "string after removing new lines: " HelloGeeksForGeeks
Method 2 : Using str_replace_all() function
This function is available in stringr package which is also used to remove the new line from a character string
Syntax: str_replace_all(string, “[\r\n]” , “”)
- string is the first parameter that takes string as input.
- [\r\n] is a second parameter which is a pattern to remove new lines
- “” is the third parameter that replaces when new line occurs as empty
Example: R program to remove newline from string using stringr package
 "Original string: " Hello Forks Geeks  "string after removing new lines: "  "HelloGeeksForGeeks"
Please Login to comment...