3 Easy Ways to Print String and List Objects in R

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.

In this article, we will see various approaches to printing the list and string in R.

How to Print String and List Objects in R

3 Ways to print string and list in R.

  1. Using print() function: The print() function can print the string and list in the console.
  2. Using cat() function: The cat() function can print multiple strings on the same line.
  3. Use str() function: The str() function can print the list in the console.

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 R function that takes the string as an argument and outputs it to the console.

# Define a string
sample_string <- "Partis Temporas"

# Print the string
print(sample_string)

Output

[1] "Partis Temporas"

The above output is printed on the console when you run the code.

Using the print() function to print a list

To print a list in R, use the print() function the same way you would print 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
print(sample_list)

Output

[[1]]
[1] 11

[[2]]
[1] 21

[[3]]
[1] 19

[[4]]
[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.

The cat() function can be helpful if you want to print multiple strings on the same line.

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

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

Output

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, 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
str(sample_list)

Output

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.

Conclusion

By using the print(), cat(), or str() functions, you can print data to the console for further analysis or debugging.

That’s it.

Leave a Comment