2

I have a function that takes one argument and prints a string:

test <- function(year){
  print(paste('and year in (', year,')'))
}

I input a vector with one element year(2012) it will print this:

"and year in ( 2012 )"

How do I write the function so if I put test(c(2012,2013,2014))it prints this?

"and year in ( 2012,2013,2014 )"
collarblind
  • 4,549
  • 13
  • 31
  • 49

2 Answers2

8

You could try using ellipsis for the task, and wrap it up within toString, as it can accept an unlimited amount of values and operate on all of them at once.

test <- function(...){
  print(paste('and year in (', toString(c(...)),')'))
}

test(2012:2014)
## [1] "and year in ( 2012, 2013, 2014 )"

The advantage of this approach is that it will also work for an input such as

test(2012, 2013, 2014)
## [1] "and year in ( 2012, 2013, 2014 )"
Community
  • 1
  • 1
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
4

I believe this answer is simpler than the one by David Arenburg. Here's a slightly different solution than the one by David Arenburg. You could include another paste in the function using the collapse option. For example:

test <- function(year){
    years = paste(year, collapse = ",")

    print(paste('and year in (', years,')'))
}

And results:

test(1)
# "and year in ( 1 )"

test(c(1, 2, 3))
# "and year in ( 1,2,3 )"
Community
  • 1
  • 1
hugot
  • 946
  • 6
  • 8
  • But with `paste` you can specify which character is used to collapse the vector elements. For example, the requested format did not include spaces between elements. I know this is subtle, and perhaps irrelevant in this case... – hugot Aug 10 '15 at 15:51
  • @RichardScriven yes, you're right, I've rephrased my answer accordingly. – hugot Aug 10 '15 at 16:05