adam.888
adam.888

Reputation: 7846

Pasting text with a vector

I am trying to paste some text with a vector:

v1 <- c(16,17,18)
paste ("the numbers in v1 are:",v1) 

I would like to get: the numbers in v1 are: 16,17,18 but instead it get:

[1] "the numbers in v1 are: 16" "the numbers in v1 are: 17"
[3] "the numbers in v1 are: 18"

I would be grateful for advice to what I am doing wrong.

Upvotes: 2

Views: 50

Answers (2)

blakeoft
blakeoft

Reputation: 2400

You need to collapse v1 first:

paste("the numbers in v1 are:", paste(v1, collapse = ","))
# [1] "the numbers in v1 are: 16,17,18"

Your code will first repeat "the numbers in v1 are" until it matches the length of v1, and then it will paste the elements of the vectors together by index.

Or

sprintf('the numbers in v1 are: %s', toString(v1))
# [1] "the numbers in v1 are: 16, 17, 18"

Upvotes: 5

SabDeM
SabDeM

Reputation: 7200

Not quite right but it achieves the goal.

cat("the numbers in v1 are:", v1)

Upvotes: 1

Related Questions