patL
patL

Reputation: 2299

Remove comma in last vector element using cat in R

I'm facing a small issue in R, but I can't figure out how to fix it.

I want to use cat to print a message in R console using sep argument in cat. This is what I've tried:

words <- c("foo", "foo2", "foo3")
cat("words not included:", "\n", words, sep = ",")
#words not included:,
#,foo,foo2,foo3

As we can see commas are inserted after : and before foo.

Then I did:

cat("words not included:", "\n", words, sep = ",", "\n")
#words not included:,
#,foo,foo2,foo3,

And my desired output is:

#words not included:
    #foo,foo2,foo3

Upvotes: 0

Views: 148

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

Just use paste with collapse here:

words <- c("foo", "foo2", "foo3")
cat(paste("words not included:", "\n", paste(words, collapse=",")))

words not included: 
 foo,foo2,foo3

Upvotes: 4

lroha
lroha

Reputation: 34501

You can use toString() instead of the sep argument in cat().

cat("words not included:", "\n", toString(words),  "\n")

words not included: 
 foo, foo2, foo3 

Upvotes: 5

Related Questions