If you use these functions, please star the repo, or cite via DOI
. Thanks!
CodeAndRoll
is a collection of custom R functions. Works with MarkdownReports
, SeuratUtils
but also as a standalone set of more than 200 productivity tools.. Many other repos/libraries of mine may have dependency on these functions. Source: own work + web (source referenced in description and/or source code). Intended for my personal use, shared because others may find (parts of it) useful.
Use the packages below:
1.) Download CodeAndRoll.R
, save as local .R
file, and source(~/path/to/CodeAndRoll.R)
:
2.) Directly source from the web:
source("https://raw.githubusercontent.com/vertesy/CodeAndRoll/master/CodeAndRoll.R")
If you encounter a bug, something doesn't work or unclear, please let me know by raising an issue on CodeAndRoll – Please check if it has been asked.
After source("~/path/to/CodeAndRoll.R")
you can use any of the functions listed below. A part of the functions have a minimal example written in the .R
scripts, just below each functions definition.
The script is roughly organised in the following sections / categories:
Note that this library is under continous development. Thus not all functions here may be still in CodeAndRoll.R, and vice versa, new functions in CodeAndRoll.R may not be listed here. Backward compatibility is most often, but not always taken care of. See other files in the repo if you are missing a function.
-
Paste by point
-
Paste by (forward) slash
-
Paste by underscore
-
Paste by dash
-
kollapse by point
-
kollapse by underscore
-
kollapse by dash
-
Silent try
-
Use system voice to notify (after a long task is done)
-
Use system voice to notify (after a long task is done)
-
grep returning the value.
-
Unload a package. Source Stackoverflow.
-
Copy from clipboard (e.g. excel) to a R-formatted vector to the clipboard
-
read a comma separated string (e.g. list of gene names) and properly format it for R.
-
Read each line of a file to an element of a vector (read in new-line separated values, no header!).
-
It is essentially read.table() with file/path parsing.
-
Read in a file.
-
Read in a file. default: header defines colnames, no rownames. For rownames give the col nr. with rownames, eg. 1 The header should start with a TAB / First column name should be empty.
-
Set First Col to Row Names
-
Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
-
Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
-
Space separeted values. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
-
Read in a file with excel style named vectors, names in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
-
Fix NA issue in dataframes imported by the new read.simple.tsv. Set na_rep to NA if you want to keep NA-s
-
Read multi-sheet excel files. row_namePos = NULL for automatic names
-
Write out a matrix-like R-object to a file with as tab separated values (.tsv). Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
-
Write out a vector-like R-object to a file with as newline separated values (.vec). Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
-
Write out a list of matrices/ data frames WITH ROW- AND COLUMN- NAMES to a file with as an Excel (.xslx) file. Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
-
Append an R-object WITHOUT ROWNAMES, to an existing .tsv file of the same number of columns. Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
-
Alias for str_split_fixed in the stringr package
-
Find the n highest values in a named vector
-
Find the n lowest values in a named vector
-
Convert a dataframe column or row into a vector, keeping the corresponding dimension name.
-
Convert a dataframe column into a vector, keeping the corresponding dimension name.
-
Convert a dataframe row into a vector, keeping the corresponding dimension name.
-
Converts any vector into a numeric vector, and puts the original character values into the names of the new vector, unless it already has names. Useful for coloring a plot by categories, name-tags, etc.
-
Converts any vector into a numeric vector, and puts the original character values into the names of the new vector, unless it already has names. Useful for coloring a plot by categories, name-tags, etc.
-
Converts your input vector into a character vector, and puts the original character values into the names of the new vector, unless it already has names.
-
linear transformation to a given range of values
-
Flip the values and the names of a vector with names
-
Sort a vector by the alphanumeric order of its names (instead of its values).
-
How many entries are duplicated
-
orig =rownames(sc@expdata)
-
orig =rownames(sc@expdata)
-
Return the names where the input vector is TRUE. The input vector is converted to logical.
-
Return the vector elements whose names are partially matched
-
Omit rows with NA values from a matrix. Rows with any, or full of NA-s
-
Omit infinite values from a vector.
-
Omit zero values from a vector.
-
Percentage of true values in a logical vector, parsed as text (useful for reports.)
-
Summary stat. text formatting for logical vectors (%, length)
-
Percentage of a certain value within a vector or table.
-
Parse a sentence reporting the % of filter survival.
-
Remove values that fall outside the trailing N % of the distribution.
-
Replace every entry that is found in "replaceit", by a single value provided by "to"
-
rotate a matrix 90 degrees.
-
Sort each column of a numeric matrix / data frame.
-
Calculates the median of each row of a numeric matrix / data frame.
-
Calculates the median of each column of a numeric matrix / data frame.
-
Calculates the median of each row of a numeric matrix / data frame.
-
Calculates the median of each column of a numeric matrix / data frame.
-
Calculates the CV of each ROW of a numeric matrix / data frame.
-
Calculates the CV of each column of a numeric matrix / data frame.
-
Calculates the CV of each ROW of a numeric matrix / data frame.
-
Calculates the CV of each column of a numeric matrix / data frame.
-
Calculates the minimum of each row of a numeric matrix / data frame.
-
Calculates the minimum of each column of a numeric matrix / data frame.
-
Calculates the maximum of each row of a numeric matrix / data frame.
-
Calculates the maximum of each column of a numeric matrix / data frame.
-
Calculates the SEM of each row of a numeric matrix / data frame.
-
Calculates the SEM of each column of a numeric matrix / data frame.
-
Calculates the SEM of each row of a numeric matrix / data frame.
-
Calculates the SEM of each column of a numeric matrix / data frame.
-
Calculates the SEM of each row of a numeric matrix / data frame.
-
Calculates the SEM of each column of a numeric matrix / data frame.
-
Calculates the SEM of each row of a numeric matrix / data frame.
-
Calculates the SEM of each column of a numeric matrix / data frame.
-
Calculate Z-score over rows of data frame.
-
RETURNS A LIST. Calculates the autocorrelation of each row of a numeric matrix / data frame.
-
RETURNS A LIST. Calculates the autocorrelation of each row of a numeric matrix / data frame.
-
Autocorrelation with exact lag
-
RETURNS A Vector for the "lag" based autocorrelation. Calculates the autocorrelation of each row of a numeric matrix / data frame.
-
RETURNS A Vector for the "lag" based autocorrelation. Calculates the autocorrelation of each row of a numeric matrix / data frame.
-
divide by column
-
divide by row
-
Sort a matrix. ALTERNATIVE: dd[with(dd, order(-z, b)), ]. Source: stackoverflow.
-
Create a copy of your matrix, where every entry is replaced by the corresponding row name. Useful if you want to color by row name in a plot (where you have different number of NA-values in each row).
-
Create a copy of your matrix, where every entry is replaced by the corresponding column name. Useful if you want to color by column name in a plot (where you have different number of NA-values in each column).
-
split a data frame by a factor corresponding to columns.
-
split a data frame by a factor corresponding to columns.
-
normalize each column to 1 million
-
normalize each column to the median of all the column-sums
-
normalize each column to the median of the columns
-
trim whitespaces from the rownames
-
Subset rows and columns. It checks if the selected dimension names exist and reports if any of those they aren't found.
-
Get the subset of rows with existing rownames, report how much it could not find.
-
Get the subset of cols with existing colnames, report how much it could not find.
-
Get odd or even columns or rows of a data frame
-
combine matrices by rownames intersect
-
Merge any data frames by rownames. Required plyr package
-
Merge 2 numeric data frames by rownames
-
Take a data frame (of e.g. metadata) from your memory space, split it into vectors so you can directly use them. E.g.: Instead of metadata$color[blabla] use color[blabla]
-
A function to display correlation values for pairs() function. Default is pearson correlation, that can be set to "kendall" or "spearman".
-
A function to display correlation values for pairs() function. Default is pearson correlation, that can be set to "kendall" or "spearman".
-
cols have to be a vector of numbers corresponding to columns
-
cols have to be a vector of numbers corresponding to columns
-
Intersect any number of lists.
-
Intersect any number of list elements. Faster than reduce.
-
lapply, then unlist
-
create a list with names from ALL variables you pass on to the function
-
Split a dataframe into a list by its columns. omit.empty for the listelments; na.omit and zero.omit are applied on entries inside each list element.
-
oSplit a dataframe into a list by its rows. omit.empty for the listelments; na.omit and zero.omit are applied on entries inside each list element.
-
reorder elements of lists in your custom order of names / indices.
-
range of values in whole list
-
Combine 2 lists (of the same length) so that form every odd and every even element of a unified list. Useful for side-by-side comparisons, e.g. in wstripchart_list().
-
convert a vector to a list with certain dimensions, taken from the list it wanna resemble
-
Convert a list to a full matrix. Rows = names(union.ls(your_list)) or all names of within list elements, columns = names(your_list).
-
Convert a list to a full matrix. Designed for occurence counting, think tof table(). Rows = all ENTRIES of within your list, columns = names(your_list).
-
split a list by its names
-
split a list by its names
-
Combine 2 vectors (of the same length) so that form every odd and every even element of a unified vector.
-
Combine 2 data frames (of the same length) so that form every odd and every even element of a unified list. Useful for side-by-side comparisons, e.g. in wstripchart_list().
-
Fill up with a vector to a given length with NA-values at the end.
-
Signal clipping. Cut values above or below a threshold.
-
Signal clipping based on the input data's distribution. It clips values above or below the extreme N% of the distribution.
-
Convert a list to a vector repeating list-element names, while vector names are the list elements
-
Quasy symmetric difference of any number of vectors
-
Calculates the standard error of the mean (SEM) for a numeric vector (it excludes NA-s by default)
-
Calculates the fano factor on a numeric vector (it excludes NA-s by default)
-
Calculates the geometric mean of a numeric vector (it excludes NA-s by default)
-
Calculates the mean of the log_k of a numeric vector (it excludes NA-s by default)
-
Calculates the moving / rolling average of a numeric vector.
-
Calculates the moving / rolling standard error of the mean (SEM) on a numeric vector.
-
Calculates the moving / rolling standard error of the mean (SEM). It calculates it to the edge of the vector with incrementally smaller window-size.
-
evaluate and parse (dyn_var_caller)
-
Awesome pattern matching for a set of values in another set of values. Returns a list with all kinds of results.
-
Alias for rich.colors in gplots
-
Display the colors encoded by the numbers / color-ID-s you pass on to this function
-
Draw a barplot from ColSums of a matrix.
-
Renders the lm() function's output into a human readable text. (e.g. for subtitles)
-
Renders the lm() function's output into a human readable text. (e.g. for subtitles)
-
Renders the lm() function's output into a human readable text. (e.g. for subtitles)
-
Split a one variable by another. Calculates equal bins in splitby, and returns a list of the corresponding values in toSplit.
-
returns the name and its value, if its not FALSE.
-
Returns the name and its value, if its TRUE.
-
Returns the name and value of each element in a list of parameters.
-
Returns the name and value of each element in a list of parameters.
-
Quantile breakpoints in any data vector Source: slowkow.com.
-
create a vector from a vector of names
-
create list from a vector with the names of the elements
-
Create a matrix from 2 vectors defining the row- and column names of the matrix. Default fill value: NA.
-
Create a matrix from values in a vector repeated for each column / each row. Similar to rowNameMatrix and colNameMatrix.
-
create an N-dimensional array from N vectors defining the row-, column, etc names of the array
-
A better version of is(). It can print the first "printme" elements.
-
A dim() function that can handle if you pass on a vector: then, it gives the length.
-
A dimnames() function that can handle if you pass on a vector: it gives back the names.
-
generate a table() with a fixed set of categories. It fills up the table with missing categories, that are relevant when comparing to other vectors.
-
Stop script if the condition is met. You can parse anything (e.g. variables) in the message
-
Show the most frequent elements of a table
-
Returns the position / index of the n highest values. For equal values, it maintains the original order
-
Calculate what is the actual value of the N-th percentile in a distribution or set of numbers. Useful for calculating cutoffs, and displaying them by whist()'s "vline" paramter.
-
find second (third…) highest/lowest value in vector
-
Extract ROW order from a pheatmap object.
-
Extract COLUMN order from a pheatmap object.
-
Extract cluster ID's for ROWS of a pheatmap object.
-
Extract cluster ID's for COLUMNS of a pheatmap object.
-
Calculate the position of ROW separating lines between clusters in a pheatmap object.
-
Calculate the position of COLUMN separating lines between clusters in a pheatmap object.
-
calculate gap positions for pheatmap, based a sorted annotation vector of categories
-
Create a Matlab-like color gradient using "colorRamps".
-
For VECTORS. Auxiliary function for pheatmap. Prepares the 2 variables needed for "annotation_col" and "annotation_colors" in pheatmap
-
For data frames. Auxiliary function for pheatmap. Prepares the 2 variables needed for "annotation_col" and "annotation_colors" in pheatmap
-
fix class and color annotation in pheatmap annotation data frame's and lists.
-
For data frames. Auxiliary function for pheatmap. Prepares the 2 variables needed for "annotation_col" and "annotation_colors" in pheatmap
-
Connect Pairs of datapoints with a line on a plot.
-
numerate from x to y with additonal zeropadding
-
Report at every e.g. 1000
-
mix entries so that they differ
-
Load a package. If it does not exist, try to install it from CRAN.
-
Internal function. Checks if a variable is defined, and its value is TRUE.
-
Find points in/out-side of a circle.
-
Cumulative subtraction, opposite of cumsum()
-
A combination of head() and tail() to see both ends.
-
Sort in decreasing order.
-
Convert a list to a vector, with list elements names replicated as many times, as many elements each element had.
-
Parse current date, dot separated.
-
view the head of an object by console.
-
view the head of an object by View().
-
Test if names of two objects for being exactly equal
-
Test if two objects for being exactly equal
-
Test if two objects for being exactly equal.
-
Parse p-value from a number to a string.
-
Calculate shannon entropy
-
Convert a gene ID to title case italic
-
Convert a gene ID to italic
-
Convert a gene ID to a gene name (symbol). From / for RaceID.
-
Convert a gene ID to the chromosome. From / for RaceID.
-
Convert an name to gene ID. From / for RaceID.
-
Convert an name to gene ID, anc copy to clipboard. From / for RaceID.
-
Convert an name to gene ID. From / for RaceID.
-
Legend color. # Source: aurelienmadouasse.wordpress.com.
-
copy dimension and dimnames
-
lapply for multidimensional arrays
-
simplify 2D-list-array to a DF
-
multi dimensional lapply + arr.of.lists.2.df (simplify 2D-list-array to a DF)
-
Show distribution of the largest objects and return their names
-
Calls na.omit() and returns a clean vector
-
Take a dataframe where every entry is a string containing an html link, parse and write out
-
Parse google search query links to your list of gene symbols. Strings "prefix" and ""suffix" will be searched for together with each gene ("Human ID4 neurons"). See many additional services in DatabaseLinke.R.
-
Parse bing search query links to your list of gene symbols. Strings "prefix" and ""suffix" will be searched for together with each gene ("Human ID4 neurons"). See many additional services in DatabaseLinke.R..
-
This function converts a vector of values("yourdata") to a vector of color levels. One must define the number of colors. The limits of the color scale("zlim") or the break points for the color changes("breaks") can also be defined. When breaks and zlim are defined, breaks overrides zlim.
-
Converts your input vector into a logical vector, and puts the original character values into the names of the new vector, unless it already has names.
-
Iterate over a vector by every N-th element.
-
Source parts of another script. Source: stackoverflow.
-
Open current working directory.
-
Setup an A4 size jpeg
-
Take a list of parameters and parse a string from their names and values.
-
GC-content of a string (frequency of G and C letters among all letters).
-
Calculate pairwise euclidean distance
-
Calculate absolute value of the pairwise euclidean distance
-
reverse list hierarchy
-
add pdf as extension to a file name
-
add png as extension to a file name
-
Convert a 2-column table (data frame) into a named vector. 1st column will be used as names.
Get CodeAndRoll. Vertesy, 2020.
If you use these functions, please star the repo, or cite via DOI
. Thanks!