Christopher Bottoms
Christopher Bottoms

Reputation: 11158

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

Upvotes: 21

Views: 51894

Answers (2)

Christopher Bottoms
Christopher Bottoms

Reputation: 11158

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.

Upvotes: 12

agenis
agenis

Reputation: 8377

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"

Upvotes: 23

Related Questions