Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function handling a vector

Tags:

function

r

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 )"
like image 982
collarblind Avatar asked Aug 03 '26 01:08

collarblind


2 Answers

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 )"
like image 113
David Arenburg Avatar answered Aug 04 '26 13:08

David Arenburg


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 )"
like image 32
hugot Avatar answered Aug 04 '26 15:08

hugot