Project: Apache Spark (App Definition and Development / Streaming & Messaging)
File: sparkr.md

layout: global displayTitle: SparkR (R on Spark) title: SparkR (R on Spark) license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This will become a table of contents (this text will be scraped). {:toc} 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, ) but on large datasets. SparkR also supports distributed machine learning using MLlib. 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. <div data-lang="r" markdown="1"> The entry point into SparkR is the `SparkSession` which connects your R program to a Spark cluster. You can create a `SparkSession` using `sparkR.session` and pass in options such as the application name, any spark packages depended on, etc. Further, you can also work with SparkDataFrames via `SparkSession`. If you are working from the `sparkR` shell, the `SparkSession` should already be created for you, and you would not need to call `sparkR.session`. <div data-lang="r" markdown="1"> {% highlight r %} sparkR.session() {% endhighlight %} </div> 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 ), 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 and 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()`. <div data-lang="r" markdown="1"> {% highlight r %} if (nchar(Sys.getenv("SPARK_HOME")) < 1) { Sys.setenv(SPARK_HOME = "/home/spark") } library(SparkR, lib.loc = c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib"))) sparkR.session(master = "local[*]", sparkConfig = list(spark.driver.memory = "2g")) {% endhighlight %} </div> The following Spark driver properties can be set in `sparkConfig` with `sparkR.session` from RStudio: <table> <thead><tr><th>Property Name</th><th>Property group</th><th><code>spark-submit</code> equivalent</th></tr></thead> <tr> <td><code>spark.master</code></td> <td>Application Properties</td> <td><code>--master</code></td> </tr> <tr>

<td>Application Properties</td> <td><code>--keytab</code></td> </tr> <tr> <td><code>spark.kerberos.principal</code></td> <td>Application Properties</td> <td><code>--principal</code></td> </tr> <tr> <td><code>spark.driver.memory</code></td> <td>Application Properties</td> <td><code>--driver-memory</code></td> </tr> <tr> <td><code>spark.driver.extraClassPath</code></td> <td>Runtime Environment</td> <td><code>--driver-class-path</code></td> </tr> <tr> <td><code>spark.driver.extraJavaOptions</code></td> <td>Runtime Environment</td> <td><code>--driver-java-options</code></td> </tr> <tr> <td><code>spark.driver.extraLibraryPath</code></td> <td>Runtime Environment</td> <td><code>--driver-library-path</code></td> </tr> </table> </div> With a `SparkSession`, applications can create `SparkDataFrame`s from a local R data frame, from a , or from other . 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. <div data-lang="r" markdown="1"> {% highlight r %} df <- as.DataFrame(faithful) head(df) {% endhighlight %} </div> 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 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 , 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. <div data-lang="r" markdown="1"> {% highlight r %} sparkR.session(sparkPackages = "org.apache.spark:spark-avro{{site.SCALABINARYVERSION}}:{{site.SPARKVERSION}}") {% endhighlight %} </div> 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 . As a consequence, a regular multi-line JSON file will most often fail. <div data-lang="r" markdown="1"> {% highlight r %} people <- read.df("./examples/src/main/resources/people.json", "json") head(people) printSchema(people) people <- read.json(c("./examples/src/main/resources/people.json", "./examples/src/main/resources/people2.json")) {% endhighlight %} </div> The data sources API natively supports CSV formatted input files. For more information please refer to SparkR API documentation. <div data-lang="r" markdown="1"> {% highlight r %} df <- read.df(csvPath, "csv", header = "true", inferSchema = "true", na.strings = "NA") {% endhighlight %} </div> 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`. <div data-lang="r" markdown="1"> {% highlight r %} write.df(people, path = "people.parquet", source = "parquet", mode = "overwrite") {% endhighlight %} </div> 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 and more details can be found in the . In SparkR, by default it will attempt to create a SparkSession with Hive support enabled (`enableHiveSupport = TRUE`). <div data-lang="r" markdown="1"> {% highlight r %} sparkR.session() sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING)") sql("LOAD DATA LOCAL INPATH

INTO TABLE src") results <- sql("FROM src SELECT key, value") head(results) {% endhighlight %} </div> 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 docs: <div data-lang="r" markdown="1"> {% highlight r %} df <- as.DataFrame(faithful) df head(select(df, df$eruptions)) head(select(df, "eruptions")) head(filter(df, df$waiting < 50)) {% endhighlight %} </div> 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 <div data-lang="r" markdown="1"> {% highlight r %} head(summarize(groupBy(df, df$waiting), count = n(df$waiting))) waiting_counts <- summarize(groupBy(df, df$waiting), count = n(df$waiting)) head(arrange(waitingcounts, desc(waitingcounts$count))) {% endhighlight %} </div> In addition to standard aggregations, SparkR supports operators `cube`: <div data-lang="r" markdown="1"> {% highlight r %} head(agg(cube(df, "cyl", "disp", "gear"), avg(df$mpg))) {% endhighlight %} </div> and `rollup`: <div data-lang="r" markdown="1"> {% highlight r %} head(agg(rollup(df, "cyl", "disp", "gear"), avg(df$mpg))) {% endhighlight %} </div> SparkR also provides a number of functions that can be directly applied to columns for data processing and during aggregation. The example below shows the use of basic arithmetic functions. <div data-lang="r" markdown="1"> {% highlight r %} df$waiting_secs <- df$waiting * 60 head(df) {% endhighlight %} </div> In SparkR, we support several kinds of User-Defined Functions: 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 of returned value. <div data-lang="r" markdown="1"> {% highlight r %} 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)) {% endhighlight %} </div> 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. <div data-lang="r" markdown="1"> {% highlight r %} ldf <- dapplyCollect( df, function(x) { x <- cbind(x, "waiting_secs" = x$waiting * 60) }) head(ldf, 3) {% endhighlight %} </div> 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 . The column names of the returned `data.frame` are set by user. <div data-lang="r" markdown="1"> {% highlight r %} 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))) {% endhighlight %} </div> 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

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. <div data-lang="r" markdown="1"> {% highlight r %} result <- gapplyCollect( df, "waiting", function(key, x) { y <- data.frame(key, max(x$eruptions)) colnames(y) <- c("waiting", "max_eruption") y }) head(result[order(result$max_eruption, decreasing = TRUE), ]) {% endhighlight %} </div> 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` <div data-lang="r" markdown="1"> {% highlight r %} families <- c("gaussian", "poisson") train <- function(family) { model <- glm(Sepal.Length ~ Sepal.Width + Species, iris, family = family) summary(model) } model.summaries <- spark.lapply(families, train) print(model.summaries) {% endhighlight %} </div> If eager execution is enabled, the data will be returned to R client immediately when the `SparkDataFrame` is created. By default, eager execution is not enabled and can be enabled by setting the configuration property `spark.sql.repl.eagerEval.enabled` to `true` when the `SparkSession` is started up. Maximum number of rows and maximum number of characters per column of data to display can be controlled by `spark.sql.repl.eagerEval.maxNumRows` and `spark.sql.repl.eagerEval.truncate` configuration properties, respectively. These properties are only effective when eager execution is enabled. If these properties are not set explicitly, by default, data up to 20 rows and up to 20 characters per column will be showed. <div data-lang="r" markdown="1"> {% highlight r %} sparkR.session(master = "local[*]", sparkConfig = list(spark.sql.repl.eagerEval.enabled = "true", spark.sql.repl.eagerEval.maxNumRows = as.integer(10))) df <- createDataFrame(faithful) df2 <- arrange(summarize(groupBy(df, df$waiting), count = n(df$waiting)), "waiting") df2 {% endhighlight %} </div> Note that to enable eager execution in `sparkR` shell, add `spark.sql.repl.eagerEval.enabled=true` configuration property to the `--conf` option. 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`. <div data-lang="r" markdown="1"> {% highlight r %} people <- read.df("./examples/src/main/resources/people.json", "json") createOrReplaceTempView(people, "people") teenagers <- sql("SELECT name FROM people WHERE age >= 13 AND age <= 19") head(teenagers) {% endhighlight %} </div> SparkR supports the following machine learning algorithms currently: : : : : : : or : : : : : `Decision Tree for` `and` : `Gradient Boosted Trees for` `and` : `Random Forest for` `and` : : : : : : : : : `Kolmogorov-Smirnov Test` Under the hood, SparkR uses MLlib to train the model. Please refer to the corresponding section of MLlib user guide for example code. Users can call `summary` to print a summary of the fitted model, to make predictions on new data, and / to save/load fitted models. SparkR supports a subset of the available R formula operators for model fitting, including ~, ., :, +, and -. The following example shows how to save/load a MLlib model by SparkR. {% includeexample readwrite r/ml/ml.R %} <table> <thead><tr><th>R</th><th>Spark</th></tr></thead> <tr> <td>byte</td> <td>byte</td> </tr> <tr> <td>integer</td> <td>integer</td> </tr> <tr> <td>float</td> <td>float</td> </tr> <tr> <td>double</td> <td>double</td> </tr> <tr> <td>numeric</td> <td>double</td> </tr> <tr> <td>character</td> <td>string</td> </tr> <tr> <td>string</td> <td>string</td> </tr> <tr> <td>binary</td> <td>binary</td> </tr> <tr> <td>raw</td> <td>binary</td> </tr> <tr> <td>logical</td> <td>boolean</td> </tr> <tr> <td><a

<td>timestamp</td> </tr> <tr> <td><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/DateTimeClasses.html">POSIXlt</a></td> <td>timestamp</td> </tr> <tr> <td><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/Dates.html">Date</a></td> <td>date</td> </tr> <tr> <td>array</td> <td>array</td> </tr> <tr> <td>list</td> <td>array</td> </tr> <tr> <td>env</td> <td>map</td> </tr> </table> SparkR supports the Structured Streaming API. Structured Streaming is a scalable and fault-tolerant stream processing engine built on the Spark SQL engine. For more information see the R API on the Apache Arrow is an in-memory columnar data format that is used in Spark to efficiently transfer data between JVM and R processes. See also PySpark optimization done, . This guide targets to explain how to use Arrow optimization in SparkR with some key points. Arrow R library is available on CRAN and it can be installed as below. ```bash Rscript -e 'install.packages("arrow", repos="https://cloud.r-project.org/")' ``` Please refer for more details. Note that you must ensure that Arrow R package is installed and available on all cluster nodes. The current supported minimum version is 1.0.0; however, this might change between the minor releases since Arrow optimization in SparkR is experimental. Arrow optimization is available when converting a Spark DataFrame to an R DataFrame using the call `collect(spark_df)`, when creating a Spark DataFrame from an R DataFrame with `createDataFrame(r_df)`, when applying an R native function to each partition via `dapply(...)` and when applying an R native function to grouped data via `gapply(...)`. To use Arrow when executing these, users need to set the Spark configuration spark.sql.execution.arrow.sparkr.enabled to true first. This is disabled by default. Whether the optimization is enabled or not, SparkR produces the same results. In addition, the conversion between Spark DataFrame and R DataFrame falls back automatically to non-Arrow optimization implementation when the optimization fails for any reasons before the actual computation. <div data-lang="r" markdown="1"> {% highlight r %} sparkR.session(master = "local[*]", sparkConfig = list(spark.sql.execution.arrow.sparkr.enabled = "true")) spark_df <- createDataFrame(mtcars) collect(spark_df) collect(dapply(spark_df, function(rdf) { data.frame(rdf$gear + 1) }, structType("gear double"))) collect(gapply(spark_df, "gear", function(key, group) { data.frame(gear = key[[1]], disp = mean(group$disp) > group$disp) }, structType("gear double, disp boolean"))) {% endhighlight %} </div> Note that even with Arrow, `collect(spark_df)` results in the collection of all records in the DataFrame to the driver program and should be done on a small subset of the data. In addition, the specified output schema in `gapply(...)` and `dapply(...)` should be matched to the R DataFrame's returned by the given function. Currently, all Spark SQL data types are supported by Arrow-based conversion except `FloatType`, `BinaryType`, `ArrayType`, `StructType` and `MapType`. When loading and attaching a new package in R, it is possible to have a name , where a function is masking another function. The following functions are masked by the SparkR package: <table> <thead><tr><th>Masked function</th><th>How to Access</th></tr></thead> <tr> <td><code>cov</code> in <code>package:stats</code></td> <td><code><pre>stats::cov(x, y = NULL, use = "everything", method = c("pearson", "kendall", "spearman"))</pre></code></td> </tr> <tr> <td><code>filter</code> in <code>package:stats</code></td> <td><code><pre>stats::filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init)</pre></code></td> </tr> <tr> <td><code>sample</code> in <code>package:base</code></td> <td><code>base::sample(x, size, replace = FALSE, prob = NULL)</code></td> </tr> </table> Since part of SparkR is modeled on the `dplyr` package, certain functions in SparkR share the same names with those in `dplyr`. Depending on the load order of the two packages, some functions from the package loaded first are masked by those in the package loaded after. In such case, prefix such calls with the package name, for instance, `SparkR::cumedist(x)` or `dplyr::cumedist(x)`. You can inspect the search path in R with The migration guide is now archived .