collarblind
collarblind

Reputation: 4739

R function handling a vector

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 )"

Upvotes: 2

Views: 98

Answers (2)

David Arenburg
David Arenburg

Reputation: 92282

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 )"

Upvotes: 8

hugot
hugot

Reputation: 981

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 )"

Upvotes: 4

Related Questions