How to Convert R List to String

In R, the list is the object which contains elements of different types like strings, numbers, vectors, and even another list. R treats any data type as a string if it is written within a pair of single or double-quotes. Converting from each other is not a big problem, and R provides inbuilt functions for conversions.

Convert R List to String

To convert the list to string in R, use one of the following functions.

  1. paste()
  2. toString()

paste() in R

The paste()  is an inbuilt R function that converts its input arguments to character strings and concatenates them. The paste() method accepts two arguments: A list and collapse, and it returns the string.

listA <- list("M", "I", "L", "L", "I", "E")

str <- paste(listA, collapse = ", ")

str

Output

[1] "M, I, L, L, I, E"

You can check the type of return variable from paste() function using typeof() function.

listA <- list("M", "I", "L", "L", "I", "E")
str <- paste(listA, collapse = ", ")
str
typeof(str)

Output

[1] "M, I, L, L, I, E"
[1] "character"

You can see that the paste() function returns the character string.

toString() in R

To convert the list to string in R, use the toString() function. The toString() is an inbuilt R function that converts An R Object To a Character String.

listA <- list("M", "I", "L", "L", "I", "E")
str <- toString(listA)
str
typeof(str)

Output

[1] "M, I, L, L, I, E"
[1] "character"

You can see that toString() function returns a character string in R.

That is it for converting the list to string in R programming.

Leave a Comment