[1] 10
RaukR 2025 • R Beyond the Basics
Sebastian DiLorenzo
08-Jun-2025
Decompose the problem 🧩 🧩!

source: Wikimedia Commons
The pieces that make a function
function_name : Name of the functionfunction() : Parameters. User input
param1 : No default value. Required.param2 = 20 : Default value... : ellipses pass other arguments into functionfunction(){} : The function bodyreturn : the last line or invoked with return() function.Tip
How to add a function to your workspace
source() / library()%>% pipes sake:
myfun <- function(x, param) 🆗myfun <- function(param, x) 📵myfun <- function(x, seed = 42) 🆗myfun <- function(x, ...) 📵optionsIf you are re-using functions written by someone else — write a wrapper function around them and use the power of the ...
tool1 | Rscript | tool2 > output
source("myscript.R") in R consoleRscript myscript.Rpath/myscript.R if:
chmod +x myscript.R#!/usr/bin/env Rscript$PATH./myscript.R inputfile.vcf outputfile.vcf
./myscript.R -i inputfile.vcf -o outputfile.vcf
./myscript.R --input inputfile.vcf --output outputfile.vcf
./myscript.R --output inputfile.vcf --input outputfile.vcf
./myscript.R --output inputfile.vcf -i inputfile.vcf
Example: ./myscript.R inputfile.vcf outputfile.vcf
commandArgs()Use commandArgs() to capture whatever was passed into R as it was executed. To be clear; this is a command that is within the Rscript file.
trailingOnly = TRUEAdd trailingOnly = TRUE to suppress the first few items and get the arguments you passed to the script.
Example: ./myscript.R --input inputfile.vcf --output outputfile.vcf
getopt, optparse, argparser, …Define set of possible arguments at start of script:
samtools mpileup -uf ref.fa aln.bam | bcftools call -mv | myPythonscript.py | myRscript.R > variants.vcf
Any stdout produced by the code (print(), cat(), etc) can be piped to a new process: ./myRscript.R | myNewScript
or written to a file: ./myRscript.R > output.csv
To write a tibble as a text stream: cat(format_csv(my_tibble))