简体   繁体   中英

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

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"

The cat function both con cat enates 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 specific a separating character (eg here \\t for tab). Also, Adding a newline character (ie \\n ) at the end is also recommended if you have any other output or a command prompt afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM