20

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
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99

2 Answers2

22

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"
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
agenis
  • 8,069
  • 5
  • 53
  • 102
12

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.

Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
  • 3
    also, `paste(..., collapse="\t")` – BrodieG Mar 04 '15 at 22:49
  • 1
    Also important to note that `cat` is really _only_ good for displaying output to the user; the function only ever returns `NULL` invisibly. If you want to capture the result, you'll need to use `paste`. – joran Mar 04 '15 at 22:54
  • 1
    @BrodieG In this case, that would be `paste(c("The first three notes are: ", notes,"\n"),collapse="\t")`. Thanks! – Christopher Bottoms Mar 04 '15 at 23:00
  • @joran Very true. Here's how to capture the result for this scenario: `result <- paste(c("The first three notes are: ", notes,"\n"),collapse="\t")`. Thanks! – Christopher Bottoms Mar 04 '15 at 23:03