0

Does anyone know how to print a statement and have it followed by all the values of a vector rather than it printing the statement multiple times followed by individual values from the vector each time.

I want it to print the statement once and then all the elements of the vector. This is returning this as an example:

print(sprintf('The times of these 20 trades were %s' , as.POSIXct(timestore)))

The times of these 20 trades were 2023-06-10 19:30:56.377" [2] "The times of these 20 trades were 2023-06-10 19:30:56.377" [3] "The times of these 20 trades were 2023-06-10 19:30:56.377" [4] "The times of these 20 trades were 2023-06-10 19:30:56.377" [5] "The times of these 20 trades were 2023-06-10 19:30:56.377" [6] "The times of these 20 trades were 2023-06-10 19:30:56.377

I want it to print the statement once and then all the elements of the vector.

  • Some advice on how to get valuable answers in SO: always provide a [good reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), which should usually include your data. You can paste the output of `dput(timestore)` . No need for this particular question, but it makes testing a lot easier. – GuedesBF Aug 24 '23 at 18:33

1 Answers1

0

We can concatenate the values with paste(sep = ",") or toString():

#REPREX

statement <-"The times of these 20 trades were"

timestore <-c('2023-06-10 19:30:56.377', '2023-06-10 19:30:56.377')

#Solution

paste0(statement, ' ', toString(as.POSIXct(timestore)))

[1] "The times of these 20 trades were 2023-06-10 19:30:56.377, 2023-06-10 19:30:56.377"

paste0(statement, ' ', toString(as.POSIXct(timestore)))

We can also declare the number of trades dinamically. glue::glue is usefull for dinamically generating strings:

glue::glue("The times of these {length(timestore)} trades were {toString(timestore)}")

The times of these 2 trades were 2023-06-10 19:30:56.377, 2023-06-10 19:30:56.377

But if we just want to print several lines, one for the statement and one for every timestamp, print(c(statement, timestore)) will do the trick

GuedesBF
  • 8,409
  • 5
  • 19
  • 37