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

Time:07-21

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.

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?

CodePudding user response:

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:

  • Related