Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make the function accept as an argument a file path or object from the environment [R]

Let’s say this is my function:

library(dplyr)
library(vroom)

#input table <- /path/to/file

myfunction <- function(input_table){
  #load data
  my_table <- vroom::vroom(input_table,col_select=c(readname, transcript_start, qc_tag),show_col_types = FALSE)
  
  #do something
  output <- dplyr::filter(my_table, qc_tag=="PASS")
    
  return(output)
}

Currently, it accepts path to the input file. I would like it to accept an argument passed either as a path to file or as an object which is already present in environment.

For instance, a table which would be prefiltered according to some criteria before launching the function of interest.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know how to do it in not so elegant way by creating an alternative argument and using if else statement. Is there another option?

>Solution :

You can use generic functions to have a function behave differently depending on the type of input it receives:

fn = function(input) {UseMethod('fn')}
fn.character = function(input) {'this is a string'}
fn.data.frame = function(input) {'this is a dataframe'}

fn('string')
[1] "this is a string"

fn(data.frame('a' = 1))
[1] "this is a dataframe"

You can read more details about this technique here:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading