Learn R Programming

NOT functions, R tricks and a compilation of some miscellaneous codes to improve your R scripts

Official website: https://quickcode.obi.obianom.com ; https://quickcode.rpkg.net

NEW Function Documentation: https://quickcode.rpkg.net/reference/index2.html

R dependency: https://depends.rpkg.net/package/quickcode

Package stats: https://rpkg.net/package/quickcode

Author R scholar profile: https://scholar.rpkg.net/aut/obinna+obianom

# Install in R
install.packages("quickcode")

70+ great R functions to add to your scripts!

Featured function 1

Add one-line code in your R script to clear environment, clear console, set working directory and load files

Featured function 2

Create a super variable with unique capability and wide scope

✅ Some Quick R Examples



# Use the nullish coalescing operator using  "or()" or "%or%"
ex.V1 <- 5
ex.V2 <- NA
ex.V3 <- NULL
ex.V4 <- ""
alternative <- 500

# Give an alternative result if the test is NULL NA or empty

or(ex.V1,alternative) # result will give 5 because ex.V1 is not NULL NA or empty

ex.V1 %or% alternative # result will give 5 because ex.V1 is not NULL NA or empty

ex.V2 %or% alternative # result will give 500 because ex.V2 is NA

ex.V3 %or% alternative # result will give 500 because ex.V3 is NULL

ex.V4 %or% alternative # result will give 500 because ex.V4 is empty

# Further chaining

ex.V2 %or% ex.V1 %or% alternative # result will be 5 because ex.V2 is NA but ex.V1 is 5

ex.V2 %or% ex.V3 %or% alternative # result will be 500 because ex.V2 is NA and ex.V3 is NULL

#load libraries and print names along with versions

quickcode::libraryAll(
  dplyr,
  r2resize,
  ggplot2
)


#simple conversion between boolean types
#input type is "vector"
baba <- c(TRUE,"y","n","YES","yes",FALSE,"f","F","T","t")
as.boolean(baba,1) # return vector as Yes/No
as.boolean(baba,2) # return vector as TRUE/FALSE
as.boolean(baba,3) # return vector as 1/0

#Recommended to use "Addins" in RStudio

#Function call: Remove Empty Lines from a File
trim.file("path/to/your/file.txt")

#Detect outliers in data by IQR and Zscore methods
x <- c(1, 2, 3, 4, 100)
detect_outlier(x, summary = TRUE)
detect_outlier(z, method = "iqr", multiplier = 3)
detect_outlier(y, method = "zscore", z_threshold = 2.5)


#apply the yesNoBool to convert between boolean
#input type is "data.frame"
usedata <- data.frame(ID = number(32))
usedata #view the dataset

usedata$yess = rep(c("yes","n","no","YES","No","NO","yES","Y"),4) #create a new column
usedata #view the modified dataset

#set all yess field as standardize boolean
yesNoBool(usedata,yess, type="bin") #set all as binary 1/0
yesNoBool(usedata,yess, type="log") #set all as logical TRUE/FALSE

#initialize one or more variables

print(g) # Error: object 'g' not found

init(g,h,i,o)
print(g) # g = NULL
print(h) # h = NULL

init(r,y,u,b,value = 5)
print(r) # r = 5
print(b) # b = 5
print(z) # Error: object 'z' not found

#add keys to a vector content for use in downstream processes

ver1 <- c("Test 1","Test 2","Test 3")
add_key(ver1)

for(i in ver1){
message(sprintf("%s is the key for this %s", i$key, i$value))
}

# Introducing the super variable
# store dataset that should not be altered
newSuperVar(mtdf, value = austres) # create a super variable
head(mtdf) # view it
mtdf.class # view the store class of the variable, it cannot be changed
# it means that when the super variable is edited, the new value MUST have the same class

# create and lock super variable by default
# extra security to prevent changing
newSuperVar(mtdf3, value = beaver1, lock = TRUE)
head(mtdf3) # view
mtdf3.round(1) # round to 1 decimal places
head(mtdf3) # view
mtdf3.signif(2) # round to 2 significant digits
head(mtdf3) # view

# Task: create a new super variable to store numbers
# edit the numbers from various scopes
newSuperVar(edtvec, value = number(5))
edtvec # view content of the vector

# edtvec.set(letters) #ERROR: Cannot set to value with different class than initial value

edtvec.set(number(20)) # set to new numbers
edtvec # view output

for (pu in 1:8) {
  print(edtvec) # view output within loop
  edtvec.set(number(pu)) # set to new numbers within for loop
}

lc <- lapply(1:8, function(pu) {
  print(edtvec) # view output within loop
  edtvec.set(number(pu)) # set to new numbers within lapply loop
})

# see that the above changed the super variable easily.
# local variable will not be altered by the loop
# example
bim <- 198
lc <- lapply(1:8, function(j) {
  print(bim)
  bim <- j # will not alter the value of bim in next round
})


#check if the entry is not integer

not.integer(45) #returns TRUE
not.integer(45.) #returns TRUE
not.integer(45L) #returns FALSE

not.null(45L) #returns TRUE
not.null(h<-NULL) #returns FALSE



#clear R environment, set directory and load data
#note: the code below also automatically loads the quickcode library so that all other functions within package can be used easily


quickcode::refresh()
quickcode::clean()

#or combine with setwd and source and load

quickcode::clean(
  setwd = "/wd/",
  source = c(
  "file.R",
  "file2.R"
  ),
  load = c(
  "data.RData",
  "data2.RData"
  )
)



#shorthand for not in vector

p1 <- 4
p2 <- c(1:10)

p1 %nin% p2




#add to a vector in one code

p1 <- c(6,7,8)
p2 <- c(1,2,3)

vector_push(p1,p2)

print(p1)



#add to a data frame in one code

p1 <- data.frame(ID=1:10,ID2=1:10)
p2 <- data.frame(ID=11:20,ID2=21:30)

data_push(p1,p2,"rows")

print(p1)


#remove from a vector in one code

p1 <- c(6,7,8,1,2,3)

vector_pop(p1)

print(p1)





#remove from a data frame in one code

p1 <- data.frame(ID=1:10,ID2=1:10,CD=11:20,BD=21:30)

data_pop(p1) #remove last row

print(p1)

data_pop(p1,5) #remove last 5 rows

print(p1)



#remove columns from a data frame in one code

p1 <- data.frame(ID=1:10,ID2=1:10,ID4=1:10,CD=11:20,BD=21:30)

data_pop(p1,which = "cols") #remove last column

print(p1)

data_pop(p1,2,which = "cols") #remove last 2 columns

print(p1)

data_pop(p1,1,which = "cols") #remove last 1 column and vectorise

print(p1)

And many more useful functions including list_shuffle, in.range ...

By Obinna Obi Obianom, Creator of www.rpkg.net and www.shinyappstore.com

Copy Link

Version

Install

install.packages('quickcode')

Monthly Downloads

686

Version

1.0.6

License

MIT + file LICENSE

Maintainer

Obinna Obianom

Last Published

March 2nd, 2025

Functions in quickcode (1.0.6)

date3to1

Combine vector to create Date, or split Date into vector
data_pop_filter

Remove elements from a data matching filter
is.increasing

Check is numbers in a vector are decreasing or increasing
from_tensor_slices

Create Tensor-Like Slices from a Data Frame or Matrix
data_push

Add data to another data like array_push in PHP
duplicate

Duplicate a file with global text replacement
is.lognormal

Check if a data fits the distribution
cols.rep

Replicate Columns in a Data Frame
add.header

Addin snippet function to add header comment to a current opened file
add.sect.comment

Addin snippet function to custom section comment
geo.cv

Calculate geometric coefficient of variation, mean, or SD and round
getDate

Extract all dates from a string
getGitRepoStart

Fetch GitHub Repository Creation & Last Updated Date
is.image

Is file name extension(s) an image
pairDist

Calculate the distance of points from the center of a cluster
detect_outlier2

Advanced Outlier Detection in Numeric Data with Optional Grouping
has.error

Check if a call or expression produces errors
minus

Decrease vector by value
archivedPkg

Listing of all CRAN archived R packages
compHist

Compare histograms of two distributions
const

Mathematical constants
math.qt

Miscellaneous math computations: Corresponding m-m and quantile for confident intervals
not.data

Not a data
lastwd

Go back to previous directory
not.numeric

Not numeric
normalize.vector

Normalize a Numeric Vector to the Range [0, 1]
not.null

Not NULL
header.rmd

Snippet function to add header to a current Rmd opened file
list_shuffle

Shuffle a list object just like shuffle in PHP
na.cumsum

Cumulative Sum with NA Removal
list_push

Add elements to a list like array_push in PHP
ndecimal

Count the number of decimal places
extract_comment

Extract all comments or functions from a file
cat_to_num

Convert Categorical Values to Numeric Improvement to seq_along()
strsplit.bool

Split a string of values and return as boolean vector
switch_cols

Switch the index of two columns in a data set
strsplit.num

Split a string of numbers and return as numeric vector
read.table.print

Read in a table and show first X rows and columns
refresh

Clear environment, clear console, set work directory and load files
rcolorconst

R Color Constant
mutate_filter

Mutate only a subset of dataset intact
mix.color

Mix or Blend two or more colors
not.exists

Not exists
read.csv.print

Read a CSV and preview first X rows and columns
sub.range

Calculate the Range Difference of a Numeric Vector
summarize.envobj

Get all the environment objects and their sizes
not.image

File name extension(s) is Not an image
multihead_att

Multi-Head Attention
not.inherits

Not inherit from any of the classes specified
not.integer

Not an integer
percent_match

Function to calculate the percentage of matching between two strings
not.duplicated

Not duplicated elements
not.environment

Not an environment
clean

Clear environment, clear console, set work directory and load files
or

Nullish coalescing operator
switch_rows

Switch the index of two rows in a data set
unique_len

Combine unique() and length()
vector_pop

Remove last n elements or specified elements from a vector like array_pop in PHP
detect_outlier

Detect Outliers in a Numeric Vector
%.%

simple function chaining routine
setOnce

Set a variable only once
not.logical

Not logical
insertInText

Shiny app function to insert string to current file in RStudio
mix.cols.btw

Mix or Blend colors between two or more colors
mode.calc

Calculate the Mode of a Numeric or Character Vector
init

Initialize new variables and objects
find_packages

Fetch R package based on keyword
fAddDate

Append date to filename
plus

Increment vector by value
chain_func

Combine specific functions as store as one function
not.empty

Not empty
sort_length

Sort vector by length or file types of its content
error.out

Error coalescing operator
in.range

If number falls within a range of values and get closest values
inc

Increment vector by value
libraryAll

Load specific R libraries and clear environment
learn_rate_scheduler

Learning Rate Scheduler
vector_push

Add elements to a vector like array_push in PHP
vector_shuffle

Shuffle a vector just like shuffle in PHP
newSuperVar

Create and use a super variable with unique capabilities
rows.rep

Replicate Rows in a Data Frame
number

Generate a random number (integer)
not.vector

Not a vector
not.na

Not NA
%nin%

Not in vector or array
zscore

Calculates Z-Scores of a distribution
track_func

Track Function Usage and Performance
trim.file

Remove Empty Lines from a File
randString

Generate a random string
yesNoBool

Convert Yes/No to Binary or Logical
rDecomPkg

Check whether an R package has been decommissioned in CRAN
sample_by_column

Re-sample a dataset by column and return number of entry needed
ai.duplicate

Prompt guided duplication and editing of files
add.snippet.clear

Snippet R function to clear console and set directory
getWeekSeq

Convert Dates into Numeric Week Counts
add_key

Add index keys to a vector or data frame or list or matrix
as.boolean

Convert boolean values between formats
bionic_txt

Generate a bionic text
extract_IP

Extract all IP addresses from a string
data_pop

Remove last n rows or column or specified elements from a data frame like array_pop in PHP
data_rep

Duplicate a data rows or columns X times
data_shuffle

Shuffle a data frame just like shuffle in PHP