Learn R Programming

⚠️There's a newer version (0.5-11) of this package.Take me there.

easyr

Helpful functions from Oliver Wyman Actuarial Consulting.

easyr makes difficult operations easy.

Function categories:

  • shorthand: protect your hands and move faster by typing less when using common functions.
  • type conversion: convert fields to dates, numbers, characters, and logical.
  • data wrangling: join and replace, explore data, factor-friendly joins and binds, etc.
  • workflow: cacheing, run folder, validate data, etc.

Data:

  • nastrings: common NA character values.
  • states: U.S. State abbreviations
  • cblind: color set built by and optimized for color-blind users.

Built, shared, and managed by Oliver Wyman Actuarial Consulting.

Now accepting proposed contributions through GitHub!

Highlights

  • read.any reads many file types, automatically selecting the best read function for you, and auto-types incoming data so you don't have to.
  • jrepl joins a mapping and adds a column or replaces values where matches occur. It is optimized to use a combination inner and left join and will error out if data is duplicated in the join.
  • cc replaces paste0 to reduce typing.
  • dict returns information about a dataset's columns. fldict does the same for a folder of datasets.
  • eq handles NAs, where chaos ensues with ==.
  • crun concatenates and runs a vector of characters as a command.
  • fmat converts dates and numbers to pretty strings.
  • tonum, todate, tobool flexibly convert character vectors with minimial work.
  • Check out the detailed list of functions below for more.

Installation

You can install the latest version available on CRAN:


install.packages('easyr')
require(easyr)

Or install the latest version from github:


devtools::install_github( "oliver-wyman-actuarial/easyr" )
require(easyr)

Support

Submit an Issue or Pull Request via GitHub and the community will review it.

Functions

Here are the functions in easyr by category. Use ?functionName to view detailed documentation for a function.

Shorthand

Common operations shortened for elegance, simplicity, and speed.

NameDescription
ccShorthand paste0/paste function to make typing these common function easier. Intuitively understands how to combine various-length inputs.
coalfdplyr function "coalesce" but handles factors appropriately. Checks each argument vector starting with the first until a non-null value is found.
crunConcatenate arguments and run them as a command. Shorthand for eval( parse( text = paste0( ... ) ) ). Consider also using base::get() which can be used to get an object from a string, but only if it already exists.
ddiffDate difference function plus shorthand mdiff, qdiff, ydiff.
eqVectorized flexible equality comparison which considers NAs as a value. Returns TRUE if both values are NA, and FALSE when only one is NA.
grGet the golden ratio.
leftBehaves like Excel's left() and right() functions.
nanullFacilitates checking for missing values. NULL values can cause errors on is.na checks, and is.na can cause warnings if it is inside if() and is passed multiple values.
%ni%Not in. Opposite of %in% operator. Equivalent to x %ni% y is equivalent to ! x %in% y.
isvalOpposite of nanull.
read.txtRead the text of a file into a character variable.
rightBehaves like Excel's left() and right() functions.
other shorthand (multiple)functions to save you keystrokes : na (is.na), nan (is.nan), null (is.null), ischar (is.character), isdate (is.Date), isnum (is.numeric), tochar (as.character)
pad0Adds leading zeros to a character vector to make each value a specific length. For values shorter than length passed, leading zeros are removed.
splExtract a uniform random sample from a dataset or vector.
strxbase::str (structure) function but only for names matching a character value (regex).
wwrite function. Writes to csv without row names and automatically adds .csv to the file name if it isn't there already. Changes to .csv if another extension is passed.

Type Conversion

Helpful for setting or changing variable/vector data types.

NameDescription
atypeAuto-type a dataframe: automatically determine data types and perform conversions per column. Used by read.any to automatically set types.
char2fac, fac2charConvert all character columns to factors and vice-versa.
match.factorsModifies two datasets so matching factor columns have the same levels. Typically this is used prior to joining or bind_rows in the easyr functions bindf, ijoinf, lfjoinf.
toboolFlexible boolean conversion function.
todateFlexible date conversion function using lubridate. Works with dates in many formats, without needing to know the format in advance.
tonumFlexible number conversion for converting strings to numbers. Handles $ , ' and spaces.
xldateConverts dates from Excel integers to something usable in R.
fmatFormat numbers and dates into character quickly and easily.

Data Wrangling

Help with reading and manipulating data.

NameDescription
binbyvolBins a numerical column according to another numerical column's volume.
bindfdplyr's bind_rows doesn't work well when the data frame has factors. This function handles factors before applying bind rows.
dictGet information about a Data Frame or Data Table. Use getinfo to explore a single column instead.
drowsPull rows with a duplicated value.
getbetterintTakes bucket names of binned values such as [1e3,2e3) or [0.1234567, 0.2) and formats the values nicely into values such as 1,000-2,000 or 0.12-0.20
fldictData dictionary for all data in a folder.
getinfoGet information about a Column in a Data Frame or Data Table. Use getdatadict to explore all columns in a dataset instead.
namesxGet column names that match a pattern.
ijoinfdplyr's joins doesn't work well when the data frame has factors. This function handles factors before applying dplyr::inner_join. Also availalbe are ljoinf, rjoinf for left and right join.
jreplJoin and replace. Joins to another dataset and replaces matched values on a given column. Good for quickly grabbing values from another dataset to fill in or replace.
read.anyFlexible read function to handle many types of files, data types, etc. Reduces downstream errors from read issues. Currently handles CSV, TSV, DBF, RDS, XLS (incl. when formatted as HTML), and XLSX.
schSearch a data frame or vector. Attempts to replicate Excel search but with regex.
short_dollarsConverts numeric plot axis dollars and attaches K and divides by 1000.
short_numsShortens axis numbering to thousands or millions and adds.
sumnumSummarize all numeric columns in a dataset.
tcolTranspose operation that sets column names equal to a column in the original data.

Workflow

Operations to run projects and organize code.

NameDescription
cachingfunctions including cache.init, cache.ok, save.cache, and clear.cache.
check_equalCheck actual versus expected values and get helpful metrics back.
hashfilesCreate a hash uniquely representing the state of files or folders. Helpful for checking for changes.
runfolderRun scripts in a folder. If an error occurs, it will tell you what file had the error. Helpful for running ordered scripts.
tcmsgEasy Try/Catch implementation to return the same message on error or warning. Makes it easier to write tryCatches.
tcwarnLike tcmsg but returns a warning instead of an error when an error occurs, so code can continue to run.
validate.equalCheck that two data frames are equivalent.

Data

These data resources are also included.

NameDescription
nastringsList of strings considered NA by easyr. Includes blank strings, "NA", excel errors, etc.
statesHelpul dataset of U.S. State abbreviations and names.
cblindCharting colors optimized for and selected by colorblind individuals.

Copy Link

Version

Install

install.packages('easyr')

Monthly Downloads

329

Version

0.1-0

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Bryce Chamberlain

Last Published

November 13th, 2019

Functions in easyr (0.1-0)

ecopy

Copy to Clipboard
fac2char

Factors to Characters
right

right
null

Shorthand for is.null
ljoinf

Left Join with Factors
likedate

Like Date
read.txt

Read File as Text
nastrings

NA Strings
sumnum

Summarize All Numeric Columns
tcmsg

tryCatch with Message
clear.cache

Clear Cache
cache.init

Initialize cache.
bindf

Bind Rows with Factors
tcwarn

tryCatch with warning
hashfiles

Hash Files
jrepl

Join and Replace Values.
atype

Auto-Type
ydiff

Date Difference in Years
cache.ok

Check Cache Status
rx

Read Excel
coalf

Factor-friendly Coalesce
tobool

Convert to Logical/Boolean
isnum

Shorthand for is.numeric
isval

Is Valid / Is a Value / NA NULL Check
headers_row

Identify headers row.
na

Shorthand for is.na
namesx

Names Like
cblind

cblind
drows

Get Rows with Duplicates
dict

Get Data Dictionary
ddiff

Date difference (or difference in days).
todate

Convert to Date
binbyvol

Bin by Volume
crun

Concatenate and run.
char2fac

Characters to Factors
cc

Concatenate.
fjoinf

Full Join with Factors
read.any

Read Any File
ijoinf

Inner Join with Factors
isdate

Shorthand for lubridate::is.Date
gr

Golden Ratio
pad0

Pad with Zeros
%ni%

Not-In
left

left
runfolder

Run Folder
nanull

NA / NULL Check
rjoinf

Right Join with Factors
nan

Shorthand for is.nan
ischar

Shorthand for is.character
tonum

Convert to Number
states

states
sch

Search a Data Frame.
isfac

Shorthand for is.factor
tochar

Shorthand for as.character
strx

Structure with Like
getbetterint

Get better Int
getinfo

Get Info
match.factors

Match Factors.
rany_fixColNames

Fix column names.
tcol

Transpose at Column.
spl

Sample
qdiff

Date Difference in Quarters
w

Write
xldate

Convert Excel Number to Date
usepkg

Use Package
mdiff

Date Difference in Months
save.cache

Save Cache Saves the arguments to a cache file, using the cache.num last checked with cache.ok.
validate.equal

Validate Equal
checkeq

Check Value or Control Total
charnum

Check for Number Formatted as Character.
fldict

Get Data Dictionary for Files in Folder
fmat

Number Formatter
eq

NA-Friendly Equality Comparison