Dplyr Join Cheat Sheet



Overview

  1. R Dplyr Join Two Tables
  2. Dplyr Join Cheat Sheet Pdf
  3. Data Wrangling Dplyr Cheat Sheet
  4. Rstudio Dplyr Cheat Sheet
  5. R Dplyr Cheat Sheet
  6. Dplyr Join Cheat Sheet Excel

Dplyr provides a grammar for manipulating tables in R. This cheat sheet will guide you through the grammar, reminding you how to select, filter, arrange, mutate, summarise, group, and join. Manipulating Data with dplyr Overview. Dplyr is an R package for working with structured data both in and outside of R. Dplyr makes data manipulation for R users easy, consistent, and performant. With dplyr as an interface to manipulating Spark DataFrames, you can: Select, filter, and aggregate data.

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
Cheat

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)

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

Flights Data

R Dplyr Join Two Tables

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:

Cheat
  • 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.

Sheet

Piping

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

Grouping

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

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.

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:

  • 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:

Source: R/join.r

These are generic functions that dispatch to individual tbl methods - see themethod documentation for details of individual data sources. x andy should usually be from the same data source, but if copy isTRUE, y will automatically be copied to the same source as x.

Arguments

Dplyr Join Cheat Sheet Pdf

x, y

tbls to join

by

a character vector of variables to join by. If NULL, thedefault, *_join() will do a natural join, using all variables withcommon names across the two tables. A message lists the variables sothat you can check they're right (to suppress the message, simplyexplicitly list the variables that you want to join).

To join by different variables on x and y use a named vector.For example, by = c('a' = 'b') will match x.a toy.b.

copy

If x and y are not from the same data source,and copy is TRUE, then y will be copied into thesame src as x. This allows you to join tables across srcs, butit is a potentially expensive operation so you must opt into it.

suffix

If there are non-joined duplicate variables in x andy, these suffixes will be added to the output to disambiguate them.Should be a character vector of length 2.

...

other parameters passed onto methods, for instance, na_matchesto control how NA values are matched. See join.tbl_df for more.

keep

If TRUE the by columns are kept in the nesting joins.

name

the name of the list column nesting joins create. If NULL the name of y is used.

Join types

Currently dplyr supports four types of mutating joins, two types of filtering joins, anda nesting join.

Mutating joins combine variables from the two data.frames:

inner_join()

return all rows from x where there are matchingvalues in y, and all columns from x and y. If there are multiple matchesbetween x and y, all combination of the matches are returned.

left_join()

return all rows from x, and all columns from xand y. Rows in x with no match in y will have NA values in the newcolumns. If there are multiple matches between x and y, all combinationsof the matches are returned.

right_join()

return all rows from y, and all columns from xand y. Rows in y with no match in x will have NA values in the newcolumns. If there are multiple matches between x and y, all combinationsof the matches are returned.

full_join()

return all rows and all columns from both x and y.Where there are not matching values, returns NA for the one missing.

Filtering joins keep cases from the left-hand data.frame:

Data Wrangling Dplyr Cheat Sheet

semi_join()

return all rows from x where there are matchingvalues in y, keeping just columns from x. A semi join differs from an inner join because an inner join will returnone row of x for each matching row of y, where a semijoin will never duplicate rows of x.

anti_join()

Rstudio Dplyr Cheat Sheet

return all rows from x where there are notmatching values in y, keeping just columns from x.

Nesting joins create a list column of data.frames:

nest_join()

R Dplyr Cheat Sheet

return all rows and all columns from x. Adds alist column of tibbles. Each tibble contains all the rows from ythat match that row of x. When there is no match, the list column isa 0-row tibble with the same column names and types as y. nest_join() is the most fundamental join since you can recreate the other joins from it.An inner_join() is a nest_join() plus an tidyr::unnest(), and left_join() is anest_join() plus an unnest(.drop = FALSE).A semi_join() is a nest_join() plus a filter() where you check that every element of data hasat least one row, and an anti_join() is a nest_join() plus a filter() where you check every element has zero rows.

Dplyr Join Cheat Sheet Excel

Grouping

Groups are ignored for the purpose of joining, but the result preservesthe grouping of x.

Examples