R Data Manipulation Cheat Sheet



  1. Data Structures in R cheat sheet will help you with the basic concepts and the commands one must know to get started with it. It is helpful for the beginners as well as experienced people as it provides a quick overview of the important concepts required. Further, if you want to learn Data Structures in R, you can refer to the R tutorial.
  2. Data management in R cheat sheet; data.table cheat sheet by Erik Petrovski; data.table wide cheat sheet by DataCamp; data.table long cheat sheet by DataCamp; Advanced R cheat sheet by Arianne Colton & Sean Chen; tidyverse cheat sheet by DataCamp; Data import cheat sheet by RStudio with readr, tibble, and tidyr; Factor manipulation with forcats.
  3. CHEAT SHEET H2O.ai. H2O TO NATIVE R COERCION as.data.frame: Check if an object is a data frame, and coerce it if possible. BASIC DATA MANIPULATION c: Combine Values into a Vector or List. DATA ATTRIBUTES h2o.names: Return column names for an H 2O Frame.Also: h o colnames.
  1. R Data Manipulation Cheat Sheet Excel
  2. R Data Manipulation Cheat Sheet Example

Overview

A matrix or a data frame, the variance-covariance matrix is calculated sd(x)standard deviation of x cor(x)correlation matrix of x if it is a matrix or a data frame (1 if x is a vector) var(x, y)or cov(x, y) covariance between x and y, or between the columns of x and those of y if they are matrices or data frames. If you spend time with R regularly then you should have the basics of data manipulation & plotting down within a couple of weeks. The more esoteric functions will take time to master. These are PDF cheat sheets that can be printed out. Keep them handy as you work with R.

dplyr isan R package for working with structured data both in and outside of R.dplyr makes data manipulation for R users easy, consistent, andperformant. With dplyr as an interface to manipulating Spark DataFrames,you can:

  • Select, filter, and aggregate data
  • Use window functions (e.g. for sampling)
  • Perform joins on DataFrames
  • Collect data from Spark into R

Statements in dplyr can be chained together using pipes defined by themagrittrR package. dplyr also supports non-standardevalutionof its arguments. For more information on dplyr, see theintroduction,a guide for connecting todatabases,and a variety ofvignettes.

Reading Data

You can read data into Spark DataFrames using the followingfunctions:

FunctionDescription
spark_read_csvReads a CSV file and provides a data source compatible with dplyr
spark_read_jsonReads a JSON file and provides a data source compatible with dplyr
spark_read_parquetReads a parquet file and provides a data source compatible with dplyr

Regardless of the format of your data, Spark supports reading data froma variety of different data sources. These include data stored on HDFS(hdfs:// protocol), Amazon S3 (s3n:// protocol), or local filesavailable to the Spark worker nodes (file:// protocol)

R Data Manipulation Cheat Sheet Excel

Each of these functions returns a reference to a Spark DataFrame whichcan be used as a dplyr table (tbl).

Flights Data

This guide will demonstrate some of the basic data manipulation verbs ofdplyr by using data from the nycflights13 R package. This packagecontains data for all 336,776 flights departing New York City in 2013.It also includes useful metadata on airlines, airports, weather, andplanes. The data comes from the US Bureau of TransportationStatistics,and is documented in ?nycflights13

Connect to the cluster and copy the flights data using the copy_tofunction. Caveat: The flight data in nycflights13 is convenient fordplyr demonstrations because it is small, but in practice large datashould rarely be copied directly from R objects.

dplyr Verbs

Verbs are dplyr commands for manipulating data. When connected to aSpark DataFrame, dplyr translates the commands into Spark SQLstatements. Remote data sources use exactly the same five verbs as localdata sources. Here are the five verbs with their corresponding SQLcommands:

  • select ~ SELECT
  • filter ~ WHERE
  • arrange ~ ORDER
  • summarise ~ aggregators: sum, min, sd, etc.
  • mutate ~ operators: +, *, log, etc.

Laziness

When working with databases, dplyr tries to be as lazy as possible:

R Data Manipulation Cheat Sheet Example

  • It never pulls data into R unless you explicitly ask for it.

  • It delays doing any work until the last possible moment: it collectstogether everything you want to do and then sends it to the databasein one step.

For example, take the followingcode:

This sequence of operations never actually touches the database. It’snot until you ask for the data (e.g. by printing c4) that dplyrrequests the results from the database.

Piping

You can usemagrittrpipes to write cleaner syntax. Using the same example from above, youcan write a much cleaner version like this:

R data manipulation cheat sheet excel

Grouping

The group_by function corresponds to the GROUP BY statement in SQL.

R data manipulation cheat sheet pdfCheat

Collecting to R

You can copy data from Spark into R’s memory by using collect().

collect() executes the Spark query and returns the results to R forfurther analysis and visualization.

R Data Manipulation Cheat Sheet

SQL Translation

It’s relatively straightforward to translate R code to SQL (or indeed toany programming language) when doing simple mathematical operations ofthe form you normally use when filtering, mutating and summarizing.dplyr knows how to convert the following R functions to Spark SQL:

Window Functions

dplyr supports Spark SQL window functions. Window functions are used inconjunction with mutate and filter to solve a wide range of problems.You can compare the dplyr syntax to the query it has generated by usingdbplyr::sql_render().

Peforming Joins

It’s rare that a data analysis involves only a single table of data. Inpractice, you’ll normally have many tables that contribute to ananalysis, and you need flexible tools to combine them. In dplyr, thereare three families of verbs that work with two tables at a time:

Sheet
  • Mutating joins, which add new variables to one table from matchingrows in another.

  • Filtering joins, which filter observations from one table based onwhether or not they match an observation in the other table.

  • Set operations, which combine the observations in the data sets asif they were set elements.

All two-table verbs work similarly. The first two arguments are x andy, and provide the tables to combine. The output is always a new tablewith the same type as x.

The following statements are equivalent:

Sampling

You can use sample_n() and sample_frac() to take a random sample ofrows: use sample_n() for a fixed number and sample_frac() for afixed fraction.

Writing Data

It is often useful to save the results of your analysis or the tablesthat you have generated on your Spark cluster into persistent storage.The best option in many scenarios is to write the table out to aParquet file using thespark_write_parquetfunction. For example:

This will write the Spark DataFrame referenced by the tbl R variable tothe given HDFS path. You can use thespark_read_parquetfunction to read the same table back into a subsequent Sparksession:

You can also write data as CSV or JSON using thespark_write_csv andspark_write_jsonfunctions.

Hive Functions

Many of Hive’s built-in functions (UDF) and built-in aggregate functions(UDAF) can be called inside dplyr’s mutate and summarize. The LanguangeReferenceUDFpage provides the list of available functions.

The following example uses the datediff and current_date HiveUDFs to figure the difference between the flight_date and the currentsystem date: