Vectors are a common data structure in R. We use vectors to store a sequence of values of the same type. In this tutorial, we will look at how to print a vector in R with the help of some examples.
How to print a vector in R?
You can use the R built-in
print() function to print the contents of a vector in R. Pass the vector you want to print as an argument to the function. The following is the syntax –
# display vector print(vec)
It prints the vector in a single line with elements separated by a space.
Let’s look at some examples of displaying a vector in R. First, we will create a vector that we will be using throughout this tutorial.
# create a vector vec <- c(10, 20, 30, 40, 50)
We now have a vector containing some numbers.
Print an R vector
Let’s use the above function to print the vector,
vec created above.
# display the vector print(vec)
 10 20 30 40 50
We get the contents of the vector as the output.
Print vector as a string
Let’s now print the above vector as a string. You can use the
paste() function in R to print the contents of a vector as a single string. You can also specify a separator to use between the vector values with the
collapse parameter of the
For example, let’s convert the above vector to a string where the values are separated by a single space.
# display vector as string paste(vec, collapse = " ")
'10 20 30 40 50'
You can see that we get a string output with the vector values.
Print vector with values separated by comma
Let’s now use the
paste() function demonstrated above to print the values as a string separated by a comma.
# display vector as string with comma as separator paste(vec, collapse = ",")
You can see that the vector values in the output are comma-separated.
Alternatively, you can also use the
cat() function in R to display values in a vector as comma-separated values.
# display vector as comma separated values cat(vec, sep=",")
You can see that we get the desired result. Unlike the output from the
paste() function, the output from the
cat() function doesn’t have any quotes.
Print vector in multiple lines
You can use the
cat() function with
'\n' as the value for the
sep parameter to display vector values on separate lines in the output.
# display vector values line by line cat(vec, sep = "\n")
10 20 30 40 50
You can see that the vector values are displayed in multiple lines.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.