Crash course and cheatsheets
In most programming languages, there are the so called "Data types". However in R, they are often referred to as Objects.
In most programming languages, there are the so called "Primitive data types". However in R, they are often referred to as Atomic objects or sometimes called as "Basic types".
logical
integer
double
complex
character
raw
Functions for checking primitive data types:
typeof()
- returns acharacter
data type value of either"logical"
,"integer"
,"double"
,"complex"
,"character"
, or"raw"
.is.atomic()
- returns alogical
data type value of eitherTRUE
orFALSE
.
Alternatively, some functions can also be used in supplementary for the typeof()
function:
mode()
storage.mode()
my.list <- list( "one", "two", "three" )
cat( my.list[[1]] ) # one
cat( my.list[[2]] ) # two
cat( my.list[[3]] ) # three
Parsing command line arguments in R can be very tricky. However, the GNU-based syntax seems to make this one easy. Getting the values can easily be done if you pass them using the --parameter=argument
format. Consider the code below...
cli.R
# Set the valid run parameters
valid.run.parameters <- c( "universe", "character", "verbose" )
# Get the run arguments
run.arguments <- commandArgs(TRUE)
# Loop each argument if and only if there are arguments
if( length( run.arguments ) > 0 ) {
for ( i in 1:length( run.arguments ) ) {
# Validate if it has the --parameter=argument structure
if ( pracma::strcmpi( substr( run.arguments[i], 1, 2 ), "--" ) & grepl( "=", run.arguments[i], fixed = TRUE) ) {
# Identify which is the parameter or argument from the --parameter=argument pattern
key.pair <- stringr::str_split( run.arguments[i], "=", simplify=TRUE )
# Get the parameter from the --parameter=argument pattern
run.parameter <- gsub( "--", "", key.pair[1] )
# Get the argument from the --parameter=argument pattern
run.argument <- substr( key_pair[2], 2, nchar(key_pair[2])-1 )
# Validate if the parameter is among the valid run parameters
if ( run.parameter %in% valid.run.parameters ) {
# DO YOUR MAGIC HERE! Here is an example...
cat( run.parameter, "\n" )
cat( run.argument, "\n\n" )
}
}
# Validate if it has the --argument structure
else if ( pracma::strcmpi( substr( run.arguments[i], 1, 2 ), "--" ) ) {
run.argument <- gsub( "--", "", run.arguments[i] )
# DO YOUR MAGIC HERE! Here is an example...
cat( run.argument, "\n\n" )
}
}
}
Example
rscript cli.R --universe=MCU --character="Wade Wilson" --hobby=trolling --verbose
Output
universe
MCU
character
Wade Wilson
verbose
Notice that the --hobby=trolling
was not processed further because hobby
was not listed in the valid.run.parameters
.