Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R prevent repeated items while using paste() for vectors

Tags:

r

paste

Consider the following:

a = 1:10
paste("The list is:", a)

And the result would be:

 [1] "The list is: 1"  "The list is: 2"  "The list is: 3"  "The list is: 4" 
 [5] "The list is: 5"  "The list is: 6"  "The list is: 7"  "The list is: 8" 
 [9] "The list is: 9"  "The list is: 10"

I have solved it by:

paste("The list is:", paste(a, collapse=", "))
# "The list is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

Is there any better idea?

like image 638
Ali Avatar asked Oct 18 '12 20:10

Ali


2 Answers

I guess it depends what you want it for. If you are pasting this together to display in the R console, say as a note or information, then cat() works a bit more intuitively:

R> cat("The list is:", a, "\n")
The list is: 1 2 3 4 5 6 7 8 9 10

or

R> cat("The list is:", a, fill = TRUE)
The list is: 1 2 3 4 5 6 7 8 9 10

If you want the actual character string as an R object I don't think you'll get much simpler than the paste() idiom you show.

like image 123
Gavin Simpson Avatar answered Nov 16 '22 02:11

Gavin Simpson


You can use:

paste(c("The list is:", a), collapse= " ")
like image 37
jormaga Avatar answered Nov 16 '22 03:11

jormaga