-
Felix Cheung authored
[SPARK-20015][SPARKR][SS][DOC][EXAMPLE] Document R Structured Streaming (experimental) in R vignettes and R & SS programming guide, R example ## What changes were proposed in this pull request? Add - R vignettes - R programming guide - SS programming guide - R example Also disable spark.als in vignettes for now since it's failing (SPARK-20402) ## How was this patch tested? manually Author: Felix Cheung <felixcheung_m@hotmail.com> Closes #17814 from felixcheung/rdocss.
Felix Cheung authored[SPARK-20015][SPARKR][SS][DOC][EXAMPLE] Document R Structured Streaming (experimental) in R vignettes and R & SS programming guide, R example ## What changes were proposed in this pull request? Add - R vignettes - R programming guide - SS programming guide - R example Also disable spark.als in vignettes for now since it's failing (SPARK-20402) ## How was this patch tested? manually Author: Felix Cheung <felixcheung_m@hotmail.com> Closes #17814 from felixcheung/rdocss.
layout: global
displayTitle: SparkR (R on Spark)
title: SparkR (R on Spark)
- This will become a table of contents (this text will be scraped). {:toc}
Overview
SparkR is an R package that provides a light-weight frontend to use Apache Spark from R. In Spark {{site.SPARK_VERSION}}, SparkR provides a distributed data frame implementation that supports operations like selection, filtering, aggregation etc. (similar to R data frames, dplyr) but on large datasets. SparkR also supports distributed machine learning using MLlib.
SparkDataFrame
A SparkDataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database or a data frame in R, but with richer optimizations under the hood. SparkDataFrames can be constructed from a wide array of sources such as: structured data files, tables in Hive, external databases, or existing local R data frames.
All of the examples on this page use sample data included in R or the Spark distribution and can be run using the ./bin/sparkR
shell.
Starting Up: SparkSession
Starting Up from RStudio
You can also start SparkR from RStudio. You can connect your R program to a Spark cluster from
RStudio, R shell, Rscript or other R IDEs. To start, make sure SPARK_HOME is set in environment
(you can check Sys.getenv),
load the SparkR package, and call sparkR.session
as below. It will check for the Spark installation, and, if not found, it will be downloaded and cached automatically. Alternatively, you can also run install.spark
manually.
In addition to calling sparkR.session
,
you could also specify certain Spark driver properties. Normally these
Application properties and
Runtime Environment cannot be set programmatically, as the
driver JVM process would have been started, in this case SparkR takes care of this for you. To set
them, pass them as you would other configuration properties in the sparkConfig
argument to
sparkR.session()
.
The following Spark driver properties can be set in sparkConfig
with sparkR.session
from RStudio:
Property Name | Property group |
spark-submit equivalent |
---|---|---|
spark.master |
Application Properties | --master |
spark.yarn.keytab |
Application Properties | --keytab |
spark.yarn.principal |
Application Properties | --principal |
spark.driver.memory |
Application Properties | --driver-memory |
spark.driver.extraClassPath |
Runtime Environment | --driver-class-path |
spark.driver.extraJavaOptions |
Runtime Environment | --driver-java-options |
spark.driver.extraLibraryPath |
Runtime Environment | --driver-library-path |
Creating SparkDataFrames
With a SparkSession
, applications can create SparkDataFrame
s from a local R data frame, from a Hive table, or from other data sources.
From local data frames
The simplest way to create a data frame is to convert a local R data frame into a SparkDataFrame. Specifically we can use as.DataFrame
or createDataFrame
and pass in the local R data frame to create a SparkDataFrame. As an example, the following creates a SparkDataFrame
based using the faithful
dataset from R.
Displays the first part of the SparkDataFrame
head(df)
eruptions waiting
##1 3.600 79 ##2 1.800 54 ##3 3.333 74
{% endhighlight %}
From Data Sources
SparkR supports operating on a variety of data sources through the SparkDataFrame
interface. This section describes the general methods for loading and saving data using Data Sources. You can check the Spark SQL programming guide for more specific options that are available for the built-in data sources.
The general method for creating SparkDataFrames from data sources is read.df
. This method takes in the path for the file to load and the type of data source, and the currently active SparkSession will be used automatically.
SparkR supports reading JSON, CSV and Parquet files natively, and through packages available from sources like Third Party Projects, you can find data source connectors for popular file formats like Avro. These packages can either be added by
specifying --packages
with spark-submit
or sparkR
commands, or if initializing SparkSession with sparkPackages
parameter when in an interactive R shell or from RStudio.
We can see how to use data sources using an example JSON input file. Note that the file that is used here is not a typical JSON file. Each line in the file must contain a separate, self-contained valid JSON object. For more information, please see JSON Lines text format, also called newline-delimited JSON. As a consequence, a regular multi-line JSON file will most often fail.
SparkR automatically infers the schema from the JSON file
printSchema(people)
root
|-- age: long (nullable = true)
|-- name: string (nullable = true)
Similarly, multiple files can be read with read.json
people <- read.json(c("./examples/src/main/resources/people.json", "./examples/src/main/resources/people2.json"))
{% endhighlight %}
The data sources API natively supports CSV formatted input files. For more information please refer to SparkR read.df API documentation.
{% endhighlight %}
The data sources API can also be used to save out SparkDataFrames into multiple file formats. For example we can save the SparkDataFrame from the previous example
to a Parquet file using write.df
.
From Hive tables
You can also create SparkDataFrames from Hive tables. To do this we will need to create a SparkSession with Hive support which can access tables in the Hive MetaStore. Note that Spark should have been built with Hive support and more details can be found in the SQL programming guide. In SparkR, by default it will attempt to create a SparkSession with Hive support enabled (enableHiveSupport = TRUE
).
sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING)") sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")
Queries can be expressed in HiveQL.
results <- sql("FROM src SELECT key, value")
results is now a SparkDataFrame
head(results)
key value
1 238 val_238
2 86 val_86
3 311 val_311
{% endhighlight %}
SparkDataFrame Operations
SparkDataFrames support a number of functions to do structured data processing. Here we include some basic examples and a complete list can be found in the API docs:
Selecting rows, columns
Get basic information about the SparkDataFrame
df
SparkDataFrame[eruptions:double, waiting:double]
Select only the "eruptions" column
head(select(df, df$eruptions))
eruptions
##1 3.600 ##2 1.800 ##3 3.333
You can also pass in column name as strings
head(select(df, "eruptions"))
Filter the SparkDataFrame to only retain rows with wait times shorter than 50 mins
head(filter(df, df$waiting < 50))
eruptions waiting
##1 1.750 47 ##2 1.750 47 ##3 1.867 48
{% endhighlight %}
Grouping, Aggregation
SparkR data frames support a number of commonly used functions to aggregate data after grouping. For example we can compute a histogram of the waiting
time in the faithful
dataset as shown below
n
operator to count the number of times each waiting time appears
We use the head(summarize(groupBy(df, dfwaiting), count = n(dfwaiting)))
waiting count
##1 70 4 ##2 67 1 ##3 69 2
We can also sort the output from the aggregation to get the most common waiting times
waiting_counts <- summarize(groupBy(df, dfwaiting), count = n(dfwaiting)) head(arrange(waiting_counts, desc(waiting_counts$count)))
waiting count
##1 78 15 ##2 83 14 ##3 81 13
{% endhighlight %}
In addition to standard aggregations, SparkR supports OLAP cube operators cube
:
and rollup
:
Operating on Columns
SparkR also provides a number of functions that can directly applied to columns for data processing and during aggregation. The example below shows the use of basic arithmetic functions.
Convert waiting time from hours to seconds.
Note that we can assign this to a new column in the same SparkDataFrame
dfwaiting_secs <- dfwaiting * 60 head(df)
eruptions waiting waiting_secs
##1 3.600 79 4740 ##2 1.800 54 3240 ##3 3.333 74 4440
{% endhighlight %}
Applying User-Defined Function
In SparkR, we support several kinds of User-Defined Functions:
dapply
or dapplyCollect
Run a given function on a large dataset using dapply
Apply a function to each partition of a SparkDataFrame
. The function to be applied to each partition of the SparkDataFrame
and should have only one parameter, to which a data.frame
corresponds to each partition will be passed. The output of function should be a data.frame
. Schema specifies the row format of the resulting a SparkDataFrame
. It must match to data types of returned value.
Convert waiting time from hours to seconds.
Note that we can apply UDF to DataFrame.
schema <- structType(structField("eruptions", "double"), structField("waiting", "double"), structField("waiting_secs", "double")) df1 <- dapply(df, function(x) { x <- cbind(x, x$waiting * 60) }, schema) head(collect(df1))
eruptions waiting waiting_secs
##1 3.600 79 4740 ##2 1.800 54 3240 ##3 3.333 74 4440 ##4 2.283 62 3720 ##5 4.533 85 5100 ##6 2.883 55 3300 {% endhighlight %}
dapplyCollect
Like dapply
, apply a function to each partition of a SparkDataFrame
and collect the result back. The output of function
should be a data.frame
. But, Schema is not required to be passed. Note that dapplyCollect
can fail if the output of UDF run on all the partition cannot be pulled to the driver and fit in driver memory.
Convert waiting time from hours to seconds.
Note that we can apply UDF to DataFrame and return a R's data.frame
ldf <- dapplyCollect( df, function(x) { x <- cbind(x, "waiting_secs" = x$waiting * 60) }) head(ldf, 3)
eruptions waiting waiting_secs
##1 3.600 79 4740 ##2 1.800 54 3240 ##3 3.333 74 4440
{% endhighlight %}
gapply
or gapplyCollect
Run a given function on a large dataset grouping by input column(s) and using gapply
Apply a function to each group of a SparkDataFrame
. The function is to be applied to each group of the SparkDataFrame
and should have only two parameters: grouping key and R data.frame
corresponding to
that key. The groups are chosen from SparkDataFrame
s column(s).
The output of function should be a data.frame
. Schema specifies the row format of the resulting
SparkDataFrame
. It must represent R function's output schema on the basis of Spark data types. The column names of the returned data.frame
are set by user.
Determine six waiting times with the largest eruption time in minutes.
schema <- structType(structField("waiting", "double"), structField("max_eruption", "double")) result <- gapply( df, "waiting", function(key, x) { y <- data.frame(key, max(x$eruptions)) }, schema) head(collect(arrange(result, "max_eruption", decreasing = TRUE)))
waiting max_eruption
##1 64 5.100 ##2 69 5.067 ##3 71 5.033 ##4 87 5.000 ##5 63 4.933 ##6 89 4.900 {% endhighlight %}
gapplyCollect
Like gapply
, applies a function to each partition of a SparkDataFrame
and collect the result back to R data.frame. The output of the function should be a data.frame
. But, the schema is not required to be passed. Note that gapplyCollect
can fail if the output of UDF run on all the partition cannot be pulled to the driver and fit in driver memory.
Determine six waiting times with the largest eruption time in minutes.
result <- gapplyCollect( df, "waiting", function(key, x) { y <- data.frame(key, max(xeruptions)) colnames(y) <- c("waiting", "max_eruption") y }) head(result[order(resultmax_eruption, decreasing = TRUE), ])
waiting max_eruption
##1 64 5.100 ##2 69 5.067 ##3 71 5.033 ##4 87 5.000 ##5 63 4.933 ##6 89 4.900
{% endhighlight %}
spark.lapply
Run local R functions distributed using spark.lapply
Similar to lapply
in native R, spark.lapply
runs a function over a list of elements and distributes the computations with Spark.
Applies a function in a manner that is similar to doParallel
or lapply
to elements of a list. The results of all the computations
should fit in a single machine. If that is not the case they can do something like df <- createDataFrame(list)
and then use
dapply
Print the summary of each model
print(model.summaries)
{% endhighlight %}
Running SQL Queries from SparkR
A SparkDataFrame can also be registered as a temporary view in Spark SQL and that allows you to run SQL queries over its data.
The sql
function enables applications to run SQL queries programmatically and returns the result as a SparkDataFrame
.
Register this SparkDataFrame as a temporary view.
createOrReplaceTempView(people, "people")
SQL statements can be run by using the sql method
teenagers <- sql("SELECT name FROM people WHERE age >= 13 AND age <= 19") head(teenagers)
name
##1 Justin
{% endhighlight %}
Machine Learning
Algorithms
SparkR supports the following machine learning algorithms currently:
Classification
-
spark.logit
:Logistic Regression
-
spark.mlp
:Multilayer Perceptron (MLP)
-
spark.naiveBayes
:Naive Bayes
-
spark.svmLinear
:Linear Support Vector Machine
Regression
-
spark.survreg
:Accelerated Failure Time (AFT) Survival Model
-
spark.glm
orglm
:Generalized Linear Model (GLM)
-
spark.isoreg
:Isotonic Regression
Tree
-
spark.gbt
:Gradient Boosted Trees for
Regression
and
Classification
-
spark.randomForest
:Random Forest for
Regression
and
Classification
Clustering
-
spark.bisectingKmeans
:Bisecting k-means
-
spark.gaussianMixture
:Gaussian Mixture Model (GMM)
-
spark.kmeans
:K-Means
-
spark.lda
:Latent Dirichlet Allocation (LDA)