Skip to content
ImagineWorld

Introduction to Spark Using R

node_idnode-book_practical-predictive-analytics_chapter-09-introduction-to-spark-using-r
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleIntroduction to Spark Using R
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Introduction to Spark Using R

Section titled “Chapter 9 — Introduction to Spark Using R”

Data! Data! Data! I can’t make bricks without clay!

- Sir Arthur Conan Doyle

So far, we have learned how to perform analytics on what can be referred to as “small data”. However, as the amount of data increases, so does the size and the problem of how to analyze the vast amounts of data that is produced arises. When that occurs, we begin to approach “big data” and new approaches to solving problems develop and sometimes, new tools are needed as well.

To some extent, nothing changes. You still want high quality data. You still want to be able to examine the relationships and cast the problem within a predictive analytic framework.

What does change are the steps needed to achieve that end, bearing in mind that the data is more difficult to manage and as a result new tools have evolved to help you do that.

One of the tools that has evolved in recent years is Apache Spark.

In this chapter, we will cover some basics of Spark. We will start with a known small dataset, perform some data cleaning, and then transform this dataset into something much larger which we can use to bring into the Apache Spark environment. We will also learn how to adapt tools that we are familiar with, in order to work with Spark, and learn some new tools along the way.

At the time of writing, Spark is probably the most popular very large dataset architecture for predictive analytics. Spark is a distributed architecture which helps you manage your large data and makes it easier to analyze. Spark is built upon Hadoop and they share the same filesystem.

However, Spark is not based upon the MapReduce paradigm, and uses the resilient distributed dataset (RDD) structure in order to implement in-memory analytics and manage the parallel processing cluster across all of the nodes of the environment. What that means for analysts is that queries can be very quick, since data is retrieved from memory, which offers much quicker retrieval than disk access. Quicker access means more time for analysis, and less time waiting for results.

Here are some advantages of Spark:

  • Spark overcomes some of the limitations of memory-bound analytics, since it manages memory, and is able to optimize data access and querying.
  • Spark has its own machine learning library known as MLlib, which implements several population predictive model techniques and optimizes computational speed for algorithms involving large datasets.
  • Spark now includes the concepts of dataframes, which extends ease of use to analysts who use R or Python.
  • Spark takes advantage of redundancy and fault-tolerant aspects of Hadoop. If one node fails for whatever reason, another node will take its place so that the analytics do not fail. This is very important when working in a production environment.
  • Spark also supports other languages such as Java and Scala. Languages can be mixed within an analytics pipeline and analysts can share the same data. This can improve team collaboration and improve efficiency.

Spark runs in three different modes:

  • Standalone
  • YARN
  • MESOS

For initial deployments (and for learning), it is best to start with standalone, which allocates clusters specifically for Spark use only. Furthermore, you can run standalone mode in local mode (your computer) or via cloud computing (an example would be using Amazon AWS).

Cluster computing allows Spark to process and distribute data over many computers at once, in parallel. A cluster manager allocates resources for the cluster depending upon user requests. An important aspect of Spark is that it attempts to keep as much data in memory as needed, so that data is available for the various analyses as quickly as possible rather than having to wait to retrieve data from storage every time a query or model is specified.

Spark data is stored as RDDs, which allow different kinds of objects to be spread out over the cluster.

Parallel computing refers to the ability to perform separate computing tasks at the same time. It does this by distributing the work load. For example if a dataframe needs to simply be sorted by last name, the cluster manager can pass the various names starting with 26 letters of the alphabet to 26 different nodes, have them each sort their own letter, and then ask for them all to be returned to one place where 1 final sort will be performed. This can be quicker than if only 1 machine performed the sort.

Spark itself is written in a programming language called Scala and runs in a Java environment. However, you are not restricted to using Scala. Spark has several interfaces which are exposed through an API, which allows Spark programs to be written in these other languages:

  • R
  • Scala
  • Java
  • Python
  • Clojure

We will be demonstrating some of the examples in this chapter using SparkR. SparkR is an R package that provides a frontend to use Apache Spark from R. This allows SparkR to allow data scientists to interactively run jobs from R on a cluster. One big advantage of using SparkR, for the traditional R programmer, is that it uses some of the techniques that they already know such as the concept of dataframes is also available within SparkR.

Spark RDDs can be a bit difficult to work with, so in recent versions of Spark, Dataframe abstractions have been built on top of RDDs, which allows analysts to view data in ways that they are used to looking at them, for example, being able to view them as tables and lists. This allows many high level languages (such as R and Python) to utilize syntax which is familiar to them and to be able to integrate optimized code, which is on par with native Scala or Spark SQL.

Databrick is a company founded by the creators of Apache Spark, which offers a free environment for running Spark programs in the cloud utilizing R, Java, Scala, or Python.

I will be using the Databricks environment for illustrating the necessary coding needed to run the chapter examples. These examples use the concept of Databricks notebooks. Databricks notebooks are similar to Jupyter or Zeppelin notebooks. The notebook metaphor allows you to display code and results all in one place.

Here is a simple example of a Databricks notebook which computes a histogram of an iris’s sepal length and plots it using ggplot.

[Insert Databricks mockup 1 and databricks mockup 2 image]

As we shall see, the databricks notebook also allows you to mix different languages in one notebook; so, for example, you can construct one analysis using a combination of R, Python, and SQL code.

In order to get started:

  1. Sign up for a free Databricks account at databricks.com.
  2. Import the notebook used in this chapter.
  3. Start up a cluster.
  4. Start following along!

One of the challenges of working with Spark is finding analytic solutions when working with very large datasets. As a preparation step, in this chapter, we will build our very own large Spark dataframe.

Also note that the concept of large dataframe is obviously relative. Since the free databricks will limit the size of any dataframe created, we will end up building a 1-million-row dataframe of about 11 variables.

I will also show you how to build a similar dataset in base R, so that you can perform your own testing and be able to judge the performance benefits received from performing the analytics on Spark.

We will end up building this Spark dataframe via simulation. This will take up a good chunk of this chapter. I feel this is a better way to go rather than importing an existing public dataset in which you cannot control the makeup of the data. With a simulated dataset, you are free to size it however you like (subject to account restrictions).

However, you are always free to import whatever dataset you would like and the analytic concepts that follow will be the same.

  1. Preliminaries first, you will need to register and log on to your databricks account.
  2. Next, create a cluster. Give it a name, such as MyCluster.
  3. To conform with the examples in this chapter, make sure you choose Spark 2.1. This is very important. Since Spark is an Apache open source product, capabilities can evolve, so we want to make sure you can reproduce your code.
  4. Select Create Cluster.
  5. Allow some time for the cluster to be created. When it is completing, you will receive the Running status, as shown in the following screenshot:

The best way to run the examples in this chapter is by importing the notebook from an external site. To do this:

  1. Click on Workspace.
  2. Right-click on Training & Tutorials (or an alternate folder) and select Import.
  3. Drag the file downloaded from the publisher site into the drop area and click on Import.

See the following screenshot:

After you import your notebook, all of the code and output will appear and you will be free to follow along with the remaining code examples.

Databricks notebooks contain the written code in the cell in the upper pane, followed by any output in the lower cell, similar to the tutorial code for the ‘diamonds’ data which is displayed next.

To run the current cell, simply click on the triangle icon on the right.

  • When the cell has run, you will be able to view your output below your code. That could be a plot or the output from the console. Always check for error messages and warnings, especially if the output is not what you expect.
  • Also note that there are some situations where no output at all is produced. That may be okay, but be sure to check the timestamp on the output cell to make sure the cell was actually run:

As an alternative to importing a notebook, you can create a new notebook from the Databricks home screen and copy/paste the code in the chapter into the notebook cells. You might want to do this if you are using some of this chapter as a template and wish to add your own code.

You can use the keyboard shortcut sequence to create a new notebook.

The strategy we will use in this chapter is to first retrieve a small existing publicly available dataset (Pima Indians diabetes). Then we will perform some basic exploratory analysis, compute some key statistical properties, and then use those properties to simulate a much larger dataset that we will use to input into Spark. The key characteristics that we will use to generate this ‘big data’ will be:

  • The means/standard deviations of the variables: the goal will be to generate means and standard deviations for the large dataset, which are close to the equivalent means and standard deviations of the small dataset.
  • The correlations of the variables: since statistical modeling and analysis is largely based upon the association among the variables, the goal of the simulation will be to preserve all of the 2-way correlation numbers for the large dataset which exist in the small dataset.
  • The underlying distribution of the variables: we will assume normal distributions for all the variables, except for the outcome variables (Diabetes, versus NonDiabetes. However, we will simulate the outcomes to correspond with the proportion reflected in the sample dataset.

To build the characteristics of the Spark dataframe, we will first take a small dataset, determine the basic statistical properties of this dataset, and then build a Spark dataframe based upon these properties.

The Pima Indians diabetes dataset contains the following attributes:

  • Number of times pregnant
  • Plasma glucose concentration with two hours in an oral glucose tolerance test
  • Diastolic blood pressure (mm Hg)
  • Triceps skin fold thickness (mm)
  • 2-hour serum insulin (mu U/ml)
  • Body mass index (weight in kg/(height in m)^2)
  • Diabetes pedigree function
  • Age (years)
  • Developed diabetes (yes or no)

The data is a publicly available dataset. In fact, there are several versions of this dataset available. We will use the dataset contained within the mlbench package, which we will load into the R workspace.

After loading the notebook, a series of code ‘chunks’ will appear. This particular notebook is an R type notebook, that is, by default, code lines can be R commands, SparkR commands, or special Databricks commands (such as display).

We will see later that we can have different cells for SQL commands (notebooks starting with %sql) or even intermix Python (%python) or scala code (%scala).

to run the contents of any particular code chunk you can use the folowingkeyboard sequence:

Alternatively, use can use the run cell icon (the first triangle icon):

Now that we now how to run individual code chunks, we will begin by running the initialization code which simply tests the Databricks system to see if it is operational and also sets some options.

The initialization code merely sets some options for later use and has no real output. We will just print “Hello World” to make sure that it is working:

options(digits=3)
options(repr.plot.width = 1000, repr.plot.height = 500, repr.plot.res = 144, repr.plot.pointsize = 5)
rep_times=1000
cat("Hello World")

The output cell prints Hello World and also gives you the time it took to run, the username, time and time, as well as the cluster it ran on. Pay close attention to the length of time that each code chunk ran. It will be useful for benchmarking code at a later date.

After running the following code, we will have the PimaIndiansDiabetes R dataframe loaded and we will run the usual str() and summary() functions. Note that we need to first install the mlbench package to retrieve the data that is contained within the package.

At this point, no Spark directives are being introduced. Even though we are running in a databricks environment, the code is pure R, and you can replicate this code in your regular R environment as well.

## load the library
devtools::install_github("cran/mlbench")
library(mlbench)
data(PimaIndiansDiabetes)
str(PimaIndiansDiabetes)
summary(PimaIndiansDiabetes)

As usual, the str() and summary() functions will give you your first insights into the data. The outputs will appear in the console pane, which is typically right below the coding pane.

Note: not all output is shown.

  • The str() function tells us that there are 768 observations and 9 variables. All of the variables have been loaded as numeric, except for the target variable diabetes, which has been coded as a factor with two levels.
  • neg indicates the diabetic condition that is not present.
  • pos indicates the diabetic condition that is present.

Again, the str() is a great way to quickly get insights. Always scan for 0’s and NA’s in the first few rows and start asking yourself if it is reasonable to expect those values.

Refer to the following figure:

The summary() function breaks out the diabetes variable into counts. Of 768 observations, there are 500 negative and 268 positive observations.

Note that the summary output has detected no missing values; however, if you look closely, you can see that there are zeros present for variables that should have a measurement (glucose, pressure, insulin, and mass). A zero for the number of times pregnant is acceptable.

We will address the zeros after we perform some plotting:

As mentioned in an earlier chapter, boxplots are a good way for comparing two numeric variables. We will compare Diabetes=‘neg’ with Diabetes=‘pos’.

Position your cursor within the next cell and run the following code chunk. This code runs the boxplot() function for variables 1-7, and breaks it out by diabetes outcome:

#some basic exploratory analysis. Box plots by outcome
par(mfrow=c(2,4))
for (i in 1:7) {
boxplot(PimaIndiansDiabetes[,i] ~ PimaIndiansDiabetes$diabetes, main=names(PimaIndiansDiabetes[i]), type="l")
}

After the run is complete (it should only take a second), the following boxplots will appear under the code that was just run:

In the boxplots produced, you can see that the median values for all of the variables are always higher for the Diabetes=‘pos’ class, except for the insulin variable, which is lower. This suggests that these variables may have some effect in predicting diabetes, but that there also may be some correlation among the predictors.

We can see from the prior summary that we have no missing values; however, we can see that there are quite a few variables with values of zero, which do not make any sense. For example, it is impossible to have a zero reading for blood pressure, but it is OK to have a 0 for the number of months pregnant. So, for most of these variables, we will assume that zero was recorded for NAs and we will map the data accordingly:

  • First, we will copy the data to a new dataframe
  • Then, we will change the zeros to NAs for the five variables listed in the code:
# we see that there are 0's which are really NA's
#some 0's are really NA's, we will change them in Spark
# keep pregnant = 0
PimaIndians <- PimaIndiansDiabetes
PimaIndians$glucose[PimaIndians$glucose ==0] <- NA
PimaIndians$pressure[PimaIndians$pressure ==0] <- NA
PimaIndians$triceps[PimaIndians$triceps ==0] <- NA
PimaIndians$insulin[PimaIndians$insulin ==0] <- NA
PimaIndians$mass[PimaIndians$mass ==0] <- NA
summary(PimaIndians)

Run another summary to ensure that the zeros have become missing values (NAs):

We will now perform a simple mean imputation. However, rather than substituting with a single mean number, we will replace the NAs with the mean values based upon membership of these four groups:

  • Diabetes=pos/younger age range
  • Diabetes=neg/younger age range
  • Diabetes=neg/older age range
  • Diabetes=pos/older age range

We already have the Diabetes=neg/pos category, so how do we categorize into the younger/older age group?

We will do that by automatically calculating a cut point. To determine the cut point, we will use the cut function on the Age variable so separate it into two levels. Then we will use dplyr to compute mean values for the five variables, depending upon how the age group was cut.

  1. First, let’s see how many observations fall into each of the four groups:
library(dplyr)
PimaIndians$agegrp <- as.numeric(cut(PimaIndians$age, breaks=2))
PimaIndians %>%
group_by(diabetes,agegrp) %>% count()
  1. The output is showing the four groups which were created, along with their counts.
Source: local data frame [4 x 3]
Groups: diabetes [?]
diabetes agegrp n
1 neg 1 460
2 neg 2 40
3 pos 1 235
4 pos 2 33
  1. Next, we will substitute an imputed mean value for each of the four groups.
  2. Note that only NA values are replaced. If they are not NA, we will keep the original value. This is something to always watch out for. You usually don’t want to overwrite valid accepted values with imputed ones!
library(dplyr)
df <- PimaIndians %>%
group_by(diabetes,agegrp) %>%
mutate(
insulin.imp = mean(insulin,na.rm=TRUE),
glucose.imp = mean(glucose,na.rm=TRUE),
pressure.imp = mean(pressure,na.rm=TRUE),
triceps.imp = mean(triceps,na.rm=TRUE),
mass.imp = mean(mass,na.rm=TRUE)
)
df$insulin <- ifelse(is.na(df$insulin), df$insulin.imp, df$insulin)
df$glucose <- ifelse(is.na(df$glucose), df$glucose.imp, df$glucose)
df$pressure <- ifelse(is.na(df$pressure), df$pressure.imp,
df$pressure)
df$triceps <- ifelse(is.na(df$triceps), df$triceps.imp, df$triceps)
df$mass <- ifelse(is.na(df$mass), df$mass.imp, df$mass)

After replacing the NAs, print the resulting dataframe and compare the assigned value with the imputed value. This is just a checkpoint to make sure that your imputation went smooth and that the results are reasonable. Always look for extreme values for imputations which can tell you if something is off.

print.data.frame(head(df[,c(
"insulin", "insulin.imp",
"glucose","glucose.imp",
"pressure","pressure.imp",
"triceps","triceps.imp",
"mass","mass.imp")],10))

When you are satisfied that the imputation has been performed correctly:

  • Assign the temporary dataframe back into the PimaIndians dataframe
  • Count the number of NAs in each row

The output of the head function shows NAs no longer exist. If there are still NAs, a row will be printed:

PimaIndians <- df
head(PimaIndians[rowSums(is.na(PimaIndians)) > 0, ])

Now, we will calculate correlation and covariance matrices. This will give us a sense of how the predictor variables relate to each other. Later on, we will also use this information to construct our larger dataset:

# calculate correlation matrix and exclude NA's
correlationMatrix <- cor(PimaIndians[,1:8])
covarianceMatrix <- stats::cov(PimaIndians[,1:8])
# summarize the correlation matrix
print(correlationMatrix,digits=3)

The correlation matrix is laid out as an n*n table with the variables specified along the top and side of the matrix. To obtain the correlation of any variable with another, look up any pair of variables along the top and bottom of the matrix and refer to the number at the intersection. That is the computed correlation:

For a small number of variables, it is easy enough to scan the matrix and pick out the significant correlations. For a larger number of variables, it would make more sense to pick out the larger correlations use code similar to this which picks out correlations >.5:

df <- as.data.frame(as.table(correlationMatrix))
subset(df, abs(Freq) > 0.5 & abs(Freq) <1)

We can see a high correlation among some of the variables-age, number of pregnancies, insulin, and glucose levels have the highest levels:

> subset(df, abs(Freq) > 0.5 & abs(Freq) <1)
Var1 Var2 Freq
8 age pregnant 0.5443412
13 insulin glucose 0.5811862
30 mass triceps 0.6482139
34 glucose insulin 0.5811862
44 triceps mass 0.6482139

You can also create the scatterplots of these variables in a number of different ways.

Use the pairs() function to accomplish this using only base R:

pairs(PimaIndians[c(1,2,4,5,6,8)],pch=21)

For the following simulation section, we will need to supply the column means via a vector, so let’s calculate them now and display them as a horizontal barchart. We will calculate the column means first for the diabetes positive group and then for the diabetes negative group. Finally, we will calculate the means for the total, although we will not use them in the next section:

means.pos = colMeans(PimaIndians[PimaIndians$diabetes =='pos',1:8],na.rm=TRUE)
means.neg = colMeans(PimaIndians[PimaIndians$diabetes =='neg',1:8],na.rm=TRUE)
means.all = colMeans(PimaIndians[,1:8],na.rm=TRUE)
barplot(means.all[c(1,2,3,4,5,6,7,8)],cex.axis=.75,cex.names=.70,horiz=TRUE,space=0)

The barplot below shows the calculated means for reference only. We are not comparing them since they all have different scale levels.

Once we have calculated the mean values and covariance matrices for all of the columns, we are ready to simulate a big dataset for any number of observations we desire.

For the covariance matrix, we can either use separate matrices for the two diabetes outcomes (1,0), or use a pooled covariance matrix, which shows the correlations among the variables regardless of the outcome.

We will use the separate correlation or covariance matrices since we have enough observations for each outcome (n=500 and n=268). If either of these classes were much smaller related to the other, we could use the pooled (or total) covariance matrix instead, since that would cover a larger set of observations.

Some notes on the code which follows:

  • As a reminder, always start with a random seed prior to a simulation. That will ensure that you get the same random results every time you run the code.
  • The cor() function will compute the correlation matrix among all of the variables, while the cov() function computes the covariance matrix. The major difference between a correlation and covariance matrix is that covariance is expressed in the same units as the variables, while correlation standardizes the relationship to a value between 0 and 1. However, they essentially measure the same thing.
  • The nbins variable will divide the data into individual bins with 400 observations each. This will be handy to extract smaller samples of the data rather than performing analysis on the entire dataset. Again, this is another way of demonstrating that sampling is your friend.
  • The datasets are generated using the mvrnorm function, which takes an input of mean values (of columns 1-8), along with the covariance matrix, which we just generated. Note: to get more information about this function, you can create a new cell anywhere in this notebook and run this command, which will invoke the R help system: help(mvrnorm, package=“MASS”)
  • To increase the size of the dataframe, we generate the dataframe with n1 observations and then repeat the dataframe a specified number of times, indicated by the rep_times variable. If you feel that the simulation is taking too long, you can reduce this variable to a lower number and the simulation will complete much faster.
  • Finally, we need to distinguish between data.frame and as.DataFrame functions:
    • The data.frame is a normal R function which creates a dataframe from the arguments within the function.
      • The as.DataFrame is a SparkR function which converts the result to a Spark dataframe.
      • When in doubt, preface the function with either base:: or SparkR:: to specifically designate the package from which it is derived. Otherwise you may get an warning or error message which could be hard to debug.
  • The last code line prints out the number of rows of the Spark dataframe using the nrow() function.

Run the next code chunk:

#generate spark dataframe
set.seed(123)
n1=268
n2=500
#data loaded into spark
#use separate correlation matrix for now. May want to use 1 pooled matrix.
correlationMatrix <- cor(PimaIndians[PimaIndians$diabetes =='pos',1:8])
covarianceMatrix <- stats::cov(PimaIndians[PimaIndians$diabetes =='pos',1:8])
require(MASS)
nbins1=base::round(n1/400,0)
out_sd1 <- as.DataFrame(data.frame(data.frame(
sample.bin=base::sample(1:nbins1,n1,replace=TRUE)*(+1),
outcome=1,
mvrnorm(n1, mu = means.pos, Sigma = matrix(covarianceMatrix, ncol = 8), empirical = TRUE)
))[rep(1:n1, times=2000), ])
nrow(out_sd1)
(1)Spark Jobs
Loading required package: MASS
Attaching package: 'MASS'
The following object is masked from 'package:SparkR':
select
[1] 536000
Command took 2.88 minutes -- by r_winters at 2/13/2017, 3:15:24 PM on My Cluster

You can see that the resultant object is a Spark dataframe by issuing an str() function. The output will specifically say SparkDataFrame, followed by a description of the variables and data types. However, it will not list the number of rows:

str(out_sd1)

We just simulated the positive cases. Now, let’s set up some similar code to simulate the non-diabetes patients (outcome=0).

For the negative cases, we will also multiply sample.bin by -1, so that in the future, we know that all the positive sample.bin instances correspond to positive cases and all the negative sample.bin instances correspond to negative ones:

set.seed(123)
nbins2=base::round(n2/400,0)
correlationMatrix <- cor(PimaIndians[PimaIndians$diabetes =='neg',1:8])
covarianceMatrix <- stats::cov(PimaIndians[PimaIndians$diabetes =='neg',1:8])
out_sd2 <- as.DataFrame(data.frame(data.frame(
sample.bin=base::sample(1:nbins2,n2,replace=TRUE)*(-1),
outcome=0,
mvrnorm(n2, mu = means.neg, Sigma = matrix(covarianceMatrix, ncol = 8), empirical = TRUE)
))[rep(1:n2, times=2000), ])
nrow(out_sd2)

The output indicates that 500,000 rows were generated. Notice that it also indicates that two Spark jobs were run to obtain the result. For the curious, you can also click on the triangle icon to display detailed information about the Spark jobs from a processing standpoint, (although it contains no results output).

We now have two separate Spark dataframes corresponding to positive and negative cases. For certain types of analysis, it would make sense to keep the outcomes separate; however, for illustration purposes, we will combine them into one single dataset using the unionAll() function.

out_sd <- unionAll(out_sd1, out_sd2)
nrow(out_sd)

The output from nrow indicates a total of 768,000 rows. This number represents our original 768 rows which has been multiplied by a factor of 1000:

One of the first things I do upon creating a new data object, is to run summary statistics. There is a Spark-specific function of the R summary function known as describe(). You can the specific function summary(); however, if you do this instead of using describe(), I would preface it with SparkR:: in order to specify which version of summary you are using:

head(SparkR::summary(out_sd))

The output appears in a slightly different format than if you ran a summary on a native R dataframe, but contains the basic measures that you are looking for, count, mean, stddev, min, and max:

We can also compare this summary with the summary of the original Pima Indians dataframe, and see that the simulation has done a pretty good job of estimating the means. The number of observations is approximately 1,000 times the original size and the ratio of diabetes to nondiabetes patients has been preserved:

#compare with original dataset
summary(PimaIndiansDiabetes[,])

Now that we have produced our final Spark data frame, we can write it to disk. Then, from the next chapter onwards, we will read it back into the workspace rather than have to recreate it from scratch. If you are proceeding directly to the next chapter, you can skip this step for now:

  • We will save in Parquet file format, which is a very efficient format for Spark and SQL. The %fs (file system) directive allows you to issue a directory (or file listing) command using the ls operating system command.
  • Once the file is saved, you can validate the integrity of the file by reading it back in and assigning it to the out_sd dataframe (again).
  • Use the head command to verify that the data was read back in:
saveAsParquetFile(out_sd, "/tmp/temp.parquet")
%fs ls
out_sd <- parquetFile(sqlContext, "/tmp/temp.parquet")
head(out_sd)

In this chapter, we have learned what Spark is and learned about some of its advantages. We began to write programs which load and save data into Spark Clusters. We learned a couple of ways how we can construct our own very large Spark dataframes based upon characteristics of small datasets.

We also learned how to write Spark programs in Databricks and how to run standard R analysis and install packages. We also reinforced our knowledge of missing value imputations by substituting some missing values in the original data.

In the next chapter, we will take what we have built and start to explore the data.