Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print all the elements of a vector in a single string in R?

Sometimes I want to print all of the elements in a vector in a single string, but it still prints the elements separately:

notes <- c("do","re","mi")
print(paste("The first three notes are: ", notes,sep="\t"))

Which gives:

[1] "The first three notes are: \tdo" "The first three notes are: \tre"
[3] "The first three notes are: \tmi"

What I really want is:

The first three notes are:      do      re      mi
like image 574
Christopher Bottoms Avatar asked Mar 04 '15 22:03

Christopher Bottoms


2 Answers

The simplest way might be to combine your message and data using one c function:

paste(c("The first three notes are: ", notes), collapse=" ")
### [1] "The first three notes are:  do re mi"
like image 148
agenis Avatar answered Oct 24 '22 17:10

agenis


The cat function both concatenates the elements of the vector and prints them:

cat("The first three notes are: ", notes,"\n",sep="\t")

Which gives:

The first three notes are:      do      re      mi

The sep argument allows you to specify a separating character (e.g. here \t for tab). Also, Adding a newline character (i.e. \n) at the end is also recommended if you have any other output or a command prompt afterwards.

like image 26
Christopher Bottoms Avatar answered Oct 24 '22 18:10

Christopher Bottoms