May
May

Reputation: 17

How to output a list in a string?

I have a list called birthdays which contains numbers. I would like to output the first 5 within a string, i.e

Birthdays: 1,2,3,4,5

I have done this:

paste("Birthdays: ",head(birthdays,6))

However this outputs:

"Birthdays: 1" "Birthdays: 2" "Birthdays: 3" "Birthdays: 4" "Birthdays: 5"

And I would like it to output: "Birthdays: 1,2,3,4,5" or something similar.

Upvotes: 0

Views: 30

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226731

use the collapse= argument to paste: this concatenates the elements in a vector (you need a separate paste call for this).

paste("Birthdays: ",paste(head(birthdays,6),collapse=","))

If you literally want to output rather than save the value in a variable, try

cat("Birthdays:",paste(1:5,collapse=","),"\n")

Upvotes: 2

Related Questions