3 Easy Ways to Print String and List Objects in R

There are the following methods to print string and list in R.

  1. Using the “print()” function.
  2. Using the “cat()” function.
  3. Use the “str()” function.

Method 1: Using the print() function

An efficient and easiest way to print a string in R is to use the “print()” function. The print() is a built-in function that takes the string as an argument and outputs it to the console.

# Define a string
sample_string <- "Partis Temporas"

# Print the string


[1] "Partis Temporas"

The above output is printed on the console when you run the code. The print() is a standard function in R that takes the object you want to print as an argument and outputs it to the console.

Using the print() function to print a list

To print a list in R, use the print() function like a string. The print() function will print the list of elements.

# Define a list
sample_list <- list(11, 21, 19, 46)

# Print a list using print() function


[1] 11

[1] 21

[1] 19

[1] 46

Method 2: Using the cat() function

The cat() is a built-in R function that “outputs the objects, concatenating the representations”.  The cat() function is similar to the print() function but does not add a new line after the string.

# Define two strings
sample_string <- "Partis Temporas"
second_string <- "Avada Kedavara"

# Print the strings using the cat() function
cat(sample_string, second_string)


Partis Temporas Avada Kedavara%

You can see that the code printed two strings, “Partis Temporas” and “Avada Kedavara” on the same line, separated by a space.

Method 3: Use the str() function

To print and get in-depth details about the list in R, you can use the “str()” function. The str() function is helpful because it provides more information about the list, such as the class and length of each element.

# Define a list
sample_list <- list(11, 21, 19, 46)

# Print a list using str() function


List of 4
$ : num 11
$ : num 21
$ : num 19
$ : num 46

You can see that in addition to printing the elements of the list, the str() function also prints the class (num) and index ($) of each element.

Leave a Comment