Open In App

Remove Newline from Character String in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to remove the new line from a character string in R Programming Language.

Example:

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.

Syntax:
gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)

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

where

  • [\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.

Code:

R




# consider a string
string = "Hello\nGeeks\nFor\nGeeks\n"
  
# display string
print("Original string: ")
cat(string)
  
# string after removing new lines
print("string after removing new lines: ")
cat(gsub("[\r\n]", "", string))


Output:

[1] "Original string: "
Hello
Geeks
For
Geeks
[1] "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]” , “”)

where

  • 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

R




library(stringr)
  
# consider a string
string="Hello\nGeeks\rFor\r\nGeeks\n"
  
# display string
print("Original string: ")
cat(string)
  
# string after removing new lines
print("string after removing new lines: ")
print(str_replace_all(string, "[\r\n]" , ""))


Output:

[1] "Original string: "
Hello
Forks
Geeks
[1] "string after removing new lines: "
[1] "HelloGeeksForGeeks"


Last Updated : 23 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads