Introduction to R and Tidyverse Cheatsheet

April 13, 2023 ยท View on GitHub

The tables below consist of valuable functions and commands that will help you through this module.

Each table represents a different library/tool and the corresponding commands.

Please note that these tables are not intended to tell you all the information you need to know about each command.

The hyperlinks found in each piece of code will take you to the documentation for further information on the usage of each command. Please be aware that the documentation will generally provide information about the given function's most current version (or a recent version, depending on how often the documentation site is updated). This will usually (but not always!) match what you have installed on your machine. If you have a different version of R or other R packages, the documentation may differ from what you have installed.

Table of Contents

Base R

Read the Base R documentation.

Library/PackagePiece of codeWhat it's calledWhat it does
Base Rlibrary()LibraryLoads and attaches additional packages to the R environment.
Base R<-Assignment operatorAssigns a name to something in the R environment.
Base R[`>`](https://rdrr.io/r/base/pipeOp.html)Pipe operator
Base Rc()CombineCombines values into a vector or list.
Base R%in%"in" logical operatorChecks if the given value(s) on the left side of the operator are in the vector or other R object defined on the right side of the operator. It returns a logical TRUE or FALSE statement. This resource also provides a helpful explanation about its usage.
Base Rrm(x)RemoveRemoves object(s) x from your environment.
Base R==, <=, >=, !=Relational OperatorsThese are binary operators which allow for the comparison of values in an object.
Base Rstr(x)Object StructureGets a summary of the object x structure.
Base Rclass(x)Object ClassReturns the type of the values in object x.
Base Rnrow(x); ncol(x)Number of Rows; Number of ColumnsGet the number of rows and the number of columns in an object x, respectively.
Base Rlength(x)LengthReturns how long the object x is.
Base Rmin(x)MinimumReturns the minimum value of all values in an object x.
Base Rsum(x)SumReturns the sum of all values (values must be integer, numeric, or logical) in object x.
Base Rmean(x)MeanReturns the arithmetic mean of all values (values must be integer or numeric) in object x or logical vector x.
Base Rlog(x)LogarithmGives the natural logarithm of object x. log2(x) can be used to give the logarithm of the object in base 2. Or the base can be specified as an argument.
Base Rhead(); tail()Head; TailReturns the top 6 (head()) or bottom 6 (tail()) rows of an object in the environment by default. You can specify how many rows you want by including the n = argument.
Base Rfactor(x) or as.factor(x)FactorCoerces object x into a factor (which is used to represent categorical data). This function can be used to coerce object x into other data types, i.e., as.character, as.numeric, as.data.frame, as.matrix, etc.
Base Rlevels(x)Levels attributesReturns or sets the value of the levels in an object x.
Base Rsummary(x)Object summaryReturns a summary of the values in object x.
Base Rdata.frame()Data FrameCreates a data frame where the named arguments will be the same length.
Base RsessionInfo()Session InformationReturns the R version information, the OS, and the attached packages in the current R session.
Base Rfile.path()File pathConstructs the path to a desired file.
Base Rdir()DirectoryLists the names of the files and/or directories in the named directory.
Base Rgetwd()Get working directoryFinds the current working directory.
Base Rsetwd()Set working directoryChanges the current working directory.
Base Rdir.exists()Directory existsChecks the file path to see if the directory exists there.
Base Rdir.create()Create directoryCreates a directory at the specified path.
Base Rapply()ApplyReturns a vector or list of values after applying a specified function to values in each row/column of an object.
Base Rround()RoundRounds the values of an object to the specified number of decimal places (default is 0).
Base Rnames()NamesGets or sets the names of an object.
Base Rcolnames()Column namesGets or sets the column names of a matrix or data frame.
Base Rall.equal()All equalChecks if two R objects are nearly equal.
Base Rall()AllChecks if all of the values are TRUE in a logical vector.
Base Rt()TransposeReturns the transpose of a matrix or data frame. If given a data frame, returns a matrix.

tidyverse

Read the tidyverse package documentation, as well as the philosophy behind the tidyverse.

dplyr

Read the dplyr package documentation, and a vignette on its usage.

Library/PackagePiece of codeWhat it's calledWhat it does
dplyr/magrittr%>%Pipe operatorFunnels an object from the output of one function to input of the next function (used like the base pipe `
dplyrfilter()FilterReturns a subset of rows matching the conditions of the specified logical argument
dplyrarrange()ArrangeReorders rows in ascending order. arrange(desc()) would reorder rows in descending order.
dplyrselect()SelectSelects columns that match the specified argument
dplyrmutate()MutateAdds a new column that is a function of existing columns
dplyrsummarize()SummarizeSummarizes multiple values in an object into a single value. This function can be used with other functions to retrieve a single output value for the grouped values. summarize and summarise are synonyms in this package. However, note that this function does not work in the same manner as the base R summary function.
dplyrrename()RenameRenames designated columns while keeping all variables of the data.frame
dplyrgroup_by()Group ByGroups data into rows that contain the same specified value(s)
dplyrinner_join()Inner JoinJoins data from two data frames, retaining only the rows that are in both datasets.

ggplot2

Read the ggplot2 package documentation, an overall reference for ggplot2 functions, and a vignette on the usage of the ggplot2 aesthetics. Additional vignettes are available from the "Articles" dropdown menu on this webpage.

Library/PackagePiece of codeWhat it's calledWhat it does
ggplot2ggplot()GG PlotBegins a plot that is finished by adding layers.
ggplot2aes()Aesthetic MappingsDesignates how variables in the data object are mapped to the visual properties of the ggplot.
ggplot2geom_boxplot()BoxplotCreates a boxplot when added as a layer to a ggplot() object.
ggplot2geom_density()Density PlotCreates a smoothed plot when added as a layer to a ggplot() object based on the computed density estimate.
ggplot2geom_point()ScatterplotCreates a scatterplot when added as a layer to a ggplot() object.
ggplot2geom_line()Line plotCreates a line plot when added as a layer to a ggplot() object by connecting the points in order of the x axis variable.
ggplot2geom_hline()Horizontal lineAnnotates a plot with a horizontal line when added as a layer to a ggplot() object
ggplot2geom_vline()Vertical lineAnnotates a plot with a vertical line when added as a layer to a ggplot() object
ggplot2theme_classic()Classic ThemeDisplays ggplot without gridlines. The ggtheme documentation has descriptions on additional themes that can be used.
ggplot2labs()LabelsModify labels (axis, title, legends) on a ggplot() object.
ggplot2xlab(); ylab(); ggtitle()X Axis Labels; Y Axis Labels; GG TitleAlternative individual functions to add individual plot labels: x-axis, y-axis, and title, respectively.
ggplot2facet_wrap()Facet WrapPlots individual graphs using specified variables to subset the data.
ggplot2ggsave()GG SaveSaves the last plot in working directory.
ggplot2last_plot()Last plotReturns the last plot produced.

readr, fs, tibble tidyr

Read the readr package documentation and a vignette on its usage. Read the fs package documentation. Read the tibble package documentation and a vignette on its usage. Read the tidyr package documentation and a vignette on its usage.

Library/PackagePiece of codeWhat it's calledWhat it does
readrread_tsv()Read TSVReads in a TSV file from a specified file path. This function can be tailored to read in other common types of files, e.g. read_csv(), read_rds(), etc.
fsdir_create()Create directoryCreate a directory, unless the directory already exists.
tibblecolumn_to_rownames()Column to RownamesTransforms an existing column called by a string into the rownames.
tibblerownames_to_column()Rownames to ColumnTransforms the rownames of a data frame into a column (which is added to the start of the data frame). The string supplied as an argument will be the name of the new column.
tidyrpivot_longer()Pivot LongerLengthens a data frame by increasing the number of rows and decreasing the number of columns.