• Connect to Spark from R. The sparklyr package provides a 
    complete dplyr backend.
  • Filter and aggregate Spark datasets then bring them into R for 
    analysis and visualization.
  • Use Spark<u+2019>s distributed machine learning library from R.
  • Create extensions that call the full Spark API and provide 
    interfaces to Spark packages.

Installation

You can install the sparklyr package from CRAN as follows:

install.packages("sparklyr")

You should also install a local version of Spark for development purposes:

library(sparklyr)
spark_install(version = "1.6.2")

To upgrade to the latest version of sparklyr, run the following command and restart your r session:

devtools::install_github("rstudio/sparklyr")

If you use the RStudio IDE, you should also download the latest preview release of the IDE which includes several enhancements for interacting with Spark (see the RStudio IDE section below for more details).

Connecting to Spark

You can connect to both local instances of Spark as well as remote Spark clusters. Here we<u+2019>ll connect to a local instance of Spark via the spark_connect function:

library(sparklyr)
sc <- spark_connect(master = "local")

The returned Spark connection (sc) provides a remote dplyr data source to the Spark cluster.

For more information on connecting to remote Spark clusters see the Deployment section of the sparklyr website.

Using dplyr

We can new use all of the available dplyr verbs against the tables within the cluster.

We<u+2019>ll start by copying some datasets from R into the Spark cluster (note that you may need to install the nycflights13 and Lahman packages in order to execute this code):

install.packages(c("nycflights13", "Lahman"))
library(dplyr)
iris_tbl <- copy_to(sc, iris)
flights_tbl <- copy_to(sc, nycflights13::flights, "flights")
batting_tbl <- copy_to(sc, Lahman::Batting, "batting")
src_tbls(sc)
## [1] "batting" "flights" "iris"

To start with here<u+2019>s a simple filtering example:

# filter by departure delay and print the first few records
flights_tbl %>% filter(dep_delay == 2)
## Source:   query [6,233 x 19]
## Database: spark connection master=local[8] app=sparklyr local=TRUE
##
## year month day dep_time sched_dep_time dep_delay arr_time
## <int> <int> <int> <int> <int> <dbl> <int>
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 542 540 2 923
## 3 2013 1 1 702 700 2 1058
## 4 2013 1 1 715 713 2 911
## 5 2013 1 1 752 750 2 1025
## 6 2013 1 1 917 915 2 1206
## 7 2013 1 1 932 930 2 1219
## 8 2013 1 1 1028 1026 2 1350
## 9 2013 1 1 1042 1040 2 1325
## 10 2013 1 1 1231 1229 2 1523
## # ... with 6,223 more rows, and 12 more variables: sched_arr_time <int>,
## # arr_delay <dbl>, carrier <chr>, flight <int>, tailnum <chr>,
## # origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
## # minute <dbl>, time_hour <dbl>

Introduction to dplyr provides additional dplyr examples you can try. For example, consider the last example from the tutorial which plots data on flight delays:

delay <- flights_tbl %>%
group_by(tailnum) %>%
summarise(count = n(), dist = mean(distance), delay = mean(arr_delay)) %>%
filter(count > 20, dist < 2000, !is.na(delay)) %>%
collect # plot delays
library(ggplot2)
ggplot(delay, aes(dist, delay)) +
geom_point(aes(size = count), alpha = 1/2) +
geom_smooth() +
scale_size_area(max_size = 2)
## `geom_smooth()` using method = 'gam'

Window Functions

dplyr window functions are also supported, for example:

batting_tbl %>%
select(playerID, yearID, teamID, G, AB:H) %>%
arrange(playerID, yearID, teamID) %>%
group_by(playerID) %>%
filter(min_rank(desc(H)) <= 2 & H > 0)
## Source:   query [2.562e+04 x 7]
## Database: spark connection master=local[8] app=sparklyr local=TRUE
## Groups: playerID
##
## playerID yearID teamID G AB R H
## <chr> <int> <chr> <int> <int> <int> <int>
## 1 abbotpa01 2000 SEA 35 5 1 2
## 2 abbotpa01 2004 PHI 10 11 1 2
## 3 abnersh01 1992 CHA 97 208 21 58
## 4 abnersh01 1990 SDN 91 184 17 45
## 5 abreujo02 2015 CHA 154 613 88 178
## 6 abreujo02 2014 CHA 145 556 80 176
## 7 acevejo01 2001 CIN 18 34 1 4
## 8 acevejo01 2004 CIN 39 43 0 2
## 9 adamsbe01 1919 PHI 78 232 14 54
## 10 adamsbe01 1918 PHI 84 227 10 40
## # ... with 2.561e+04 more rows

For additional documentation on using dplyr with Spark see the dplyr section of the sparklyr website.

Using SQL

It<u+2019>s also possible to execute SQL queries directly against tables within a Spark cluster. The spark_connection object implements a DBI interface for Spark, so you can use dbGetQuery to execute SQL and return the result as an R data frame:

library(DBI)
iris_preview <- dbGetQuery(sc, "SELECT * FROM iris LIMIT 10")
iris_preview
##    Sepal_Length Sepal_Width Petal_Length Petal_Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## 7 4.6 3.4 1.4 0.3 setosa
## 8 5.0 3.4 1.5 0.2 setosa
## 9 4.4 2.9 1.4 0.2 setosa
## 10 4.9 3.1 1.5 0.1 setosa

Machine Learning

You can orchestrate machine learning algorithms in a Spark cluster via the machine learning functions within sparklyr. These functions connect to a set of high-level APIs built on top of DataFrames that help you create and tune machine learning workflows.

Here<u+2019>s an example where we use ml_linear_regression to fit a linear regression model. We<u+2019>ll use the built-in mtcars dataset, and see if we can predict a car<u+2019>s fuel consumption (mpg) based on its weight (wt), and the number of cylinders the engine contains (cyl). We<u+2019>ll assume in each case that the relationship between mpg and each of our features is linear.

# copy mtcars into spark
mtcars_tbl <- copy_to(sc, mtcars) # transform our data set, and then partition into 'training', 'test'
partitions <- mtcars_tbl %>%
filter(hp >= 100) %>%
mutate(cyl8 = cyl == 8) %>%
sdf_partition(training = 0.5, test = 0.5, seed = 1099) # fit a linear model to the training dataset
fit <- partitions$training %>%
ml_linear_regression(response = "mpg", features = c("wt", "cyl"))
## * No rows dropped by 'na.omit' call
fit
## Call: ml_linear_regression(., response = "mpg", features = c("wt", "cyl"))
##
## Coefficients:
## (Intercept) wt cyl
## 37.066699 -2.309504 -1.639546

For linear regression models produced by Spark, we can use summary() to learn a bit more about the quality of our fit, and the statistical significance of each of our predictors.

summary(fit)
## Call: ml_linear_regression(., response = "mpg", features = c("wt", "cyl"))
##
## Deviance Residuals::
## Min 1Q Median 3Q Max
## -2.6881 -1.0507 -0.4420 0.4757 3.3858
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 37.06670 2.76494 13.4059 2.981e-07 ***
## wt -2.30950 0.84748 -2.7252 0.02341 *
## cyl -1.63955 0.58635 -2.7962 0.02084 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## R-Squared: 0.8665
## Root Mean Squared Error: 1.799

Spark machine learning supports a wide array of algorithms and feature transformations and as illustrated above it<u+2019>s easy to chain these functions together with dplyr pipelines. To learn more see the machine learning section.

Reading and Writing Data

You can read and write data in CSV, JSON, and Parquet formats. Data can be stored in HDFS, S3, or on the local filesystem of cluster nodes.

temp_csv <- tempfile(fileext = ".csv")
temp_parquet <- tempfile(fileext = ".parquet")
temp_json <- tempfile(fileext = ".json") spark_write_csv(iris_tbl, temp_csv)
iris_csv_tbl <- spark_read_csv(sc, "iris_csv", temp_csv) spark_write_parquet(iris_tbl, temp_parquet)
iris_parquet_tbl <- spark_read_parquet(sc, "iris_parquet", temp_parquet) spark_write_json(iris_tbl, temp_json)
iris_json_tbl <- spark_read_json(sc, "iris_json", temp_json) src_tbls(sc)
## [1] "batting"      "flights"      "iris"         "iris_csv"
## [5] "iris_json" "iris_parquet" "mtcars"

Extensions

The facilities used internally by sparklyr for its dplyr and machine learning interfaces are available to extension packages. Since Spark is a general purpose cluster computing system there are many potential applications for extensions (e.g.<u+00a0>interfaces to custom machine learning pipelines, interfaces to 3rd party Spark packages, etc.).

Here<u+2019>s a simple example that wraps a Spark text file line counting function with an R function:

# write a CSV
tempfile <- tempfile(fileext = ".csv")
write.csv(nycflights13::flights, tempfile, row.names = FALSE, na = "") # define an R interface to Spark line counting
count_lines <- function(sc, path) {
spark_context(sc) %>%
invoke("textFile", path, 1L) %>%
invoke("count")
} # call spark to count the lines of the CSV
count_lines(sc, tempfile)
## [1] 336777

To learn more about creating extensions see the Extensions section of the sparklyr website.

Table Utilities

You can cache a table into memory with:

tbl_cache(sc, "batting")

and unload from memory using:

tbl_uncache(sc, "batting")

Connection Utilities

You can view the Spark web console using the spark_web function:

spark_web(sc)

You can show the log using the spark_log function:

spark_log(sc, n = 10)
## 17/02/03 15:34:17 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 91 (/var/folders/fz/v6wfsg2x1fb1rw4f6r0x4jwm0000gn/T//RtmpZqMbDE/file8f2b280ac4e5.csv MapPartitionsRDD[363] at textFile at NativeMethodAccessorImpl.java:-2)
## 17/02/03 15:34:17 INFO TaskSchedulerImpl: Adding task set 91.0 with 1 tasks
## 17/02/03 15:34:17 INFO TaskSetManager: Starting task 0.0 in stage 91.0 (TID 177, localhost, partition 0,PROCESS_LOCAL, 2430 bytes)
## 17/02/03 15:34:17 INFO Executor: Running task 0.0 in stage 91.0 (TID 177)
## 17/02/03 15:34:17 INFO HadoopRDD: Input split: file:/var/folders/fz/v6wfsg2x1fb1rw4f6r0x4jwm0000gn/T/RtmpZqMbDE/file8f2b280ac4e5.csv:0+33313106
## 17/02/03 15:34:17 INFO Executor: Finished task 0.0 in stage 91.0 (TID 177). 2082 bytes result sent to driver
## 17/02/03 15:34:17 INFO TaskSetManager: Finished task 0.0 in stage 91.0 (TID 177) in 116 ms on localhost (1/1)
## 17/02/03 15:34:17 INFO DAGScheduler: ResultStage 91 (count at NativeMethodAccessorImpl.java:-2) finished in 0.117 s
## 17/02/03 15:34:17 INFO TaskSchedulerImpl: Removed TaskSet 91.0, whose tasks have all completed, from pool
## 17/02/03 15:34:17 INFO DAGScheduler: Job 61 finished: count at NativeMethodAccessorImpl.java:-2, took 0.119612 s

Finally, we disconnect from Spark:

RStudio IDE

The latest RStudio Preview Release of the RStudio IDE includes integrated support for Spark and the sparklyr package, including tools for:

  • Creating and managing Spark connections
  • Browsing the tables and columns of Spark DataFrames
  • Previewing the first 1,000 rows of Spark DataFrames

Once you<u+2019>ve installed the sparklyr package, you should find a new Spark pane within the IDE. This pane includes a New Connection dialog which can be used to make connections to local or remote Spark instances:

Once you<u+2019>ve connected to Spark you<u+2019>ll be able to browse the tables contained within the Spark cluster:

The Spark DataFrame preview uses the standard RStudio data viewer:

The RStudio IDE features for sparklyr are available now as part of the RStudio Preview Release.

Using H2O

rsparkling is a CRAN package from H2O that extends sparklyr to provide an interface into Sparkling Water. For instance, the following example installs, configures and runs h2o.glm:

options(rsparkling.sparklingwater.version = "1.6.8")

library(rsparkling)
library(sparklyr)
library(dplyr)
library(h2o) sc <- spark_connect(master = "local", version = "1.6.2")
mtcars_tbl <- copy_to(sc, mtcars, "mtcars") mtcars_h2o <- as_h2o_frame(sc, mtcars_tbl, strict_version_check = FALSE) mtcars_glm <- h2o.glm(x = c("wt", "cyl"),
y = "mpg",
training_frame = mtcars_h2o,
lambda_search = TRUE)
mtcars_glm
## Model Details:
## ==============
##
## H2ORegressionModel: glm
## Model ID: GLM_model_R_1486164877174_1
## GLM Model: summary
## family link regularization
## 1 gaussian identity Elastic Net (alpha = 0.5, lambda = 0.1013 )
## lambda_search
## 1 nlambda = 100, lambda.max = 10.132, lambda.min = 0.1013, lambda.1se = -1.0
## number_of_predictors_total number_of_active_predictors
## 1 2 2
## number_of_iterations training_frame
## 1 0 frame_rdd_33
##
## Coefficients: glm coefficients
## names coefficients standardized_coefficients
## 1 Intercept 38.941654 20.090625
## 2 cyl -1.468783 -2.623132
## 3 wt -3.034558 -2.969186
##
## H2ORegressionMetrics: glm
## ** Reported on training data. **
##
## MSE: 6.017684
## RMSE: 2.453097
## MAE: 1.940985
## RMSLE: 0.1114801
## Mean Residual Deviance : 6.017684
## R^2 : 0.8289895
## Null Deviance :1126.047
## Null D.o.F. :31
## Residual Deviance :192.5659
## Residual D.o.F. :29
## AIC :156.2425

Connecting through Livy

Livy enables remote connections to Apache Spark clusters. Connecting to Spark clusters through Livy is under experimental development in sparklyr. Please post any feedback or questions as a GitHub issue as needed.

Before connecting to Livy, you will need the connection information to an existing service running Livy. Otherwise, to test livy in your local environment, you can install it and run it locally as follows:

To connect, use the Livy service address as master and method = "livy" in spark_connect. Once connection completes, use sparklyr as usual, for instance:

sc <- spark_connect(master = "http://localhost:8998", method = "livy")
copy_to(sc, iris)
## Source:   query [150 x 5]
## Database: spark connection master=http://localhost:8998 app= local=FALSE
##
## Sepal_Length Sepal_Width Petal_Length Petal_Width Species
## <dbl> <dbl> <dbl> <dbl> <chr>
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## 7 4.6 3.4 1.4 0.3 setosa
## 8 5.0 3.4 1.5 0.2 setosa
## 9 4.4 2.9 1.4 0.2 setosa
## 10 4.9 3.1 1.5 0.1 setosa
## # ... with 140 more rows

Once you are done using livy locally, you should stop this service with:

To connect to remote livy clusters that support basic authentication connect as:

config <- livy_config_auth("<username>", "<password">)
sc <- spark_connect(master = "<address>", method = "livy", config = config)
spark_disconnect(sc)

Links

License

Apache License 2.0 | file LICENSE

Developers

  • Javier Luraschi 
    Author, maintainer
  • Kevin Ushey 
    Author
  • JJ Allaire 
    Author
  • The Apache Software Foundation 
    Author, copyright<u+00a0>holder
  • All authors...

Dev status

Developed by Javier Luraschi, Kevin Ushey, JJ Allaire, The Apache Software Foundation.

Site built with pkgdown.

参考 http://spark.rstudio.com/

http://alitrack.com/2016/11/01/sparklyr-r%E8%AF%AD%E8%A8%80%E8%AE%BF%E9%97%AEspark%E7%9A%84%E5%8F%A6%E5%A4%96%E4%B8%80%E7%A7%8D%E6%96%B9%E6%B3%95/

sparklyr-R语言访问Spark的另外一种方法的更多相关文章

  1. R语言中样本平衡的几种方法

    R语言中样本平衡的几种方法 在对不平衡的分类数据集进行建模时,机器学习算法可能并不稳定,其预测结果甚至可能是有偏的,而预测精度此时也变得带有误导性.在不平衡的数据中,任一算法都没法从样本量少的类中获取 ...

  2. R语言读取excel文件的3种方法

    R读取excel文件中数据的方法: 电脑有一个excel文件,原始的文件路径是:E:\R workshop\mydata\biom excel数据为5乘2阶矩阵,元素为                ...

  3. shell中调用R语言并传入参数的两种步骤

    shell中调用R语言并传入参数的两种方法 第一种: Rscript myscript.R R脚本的输出 第二种: R CMD BATCH myscript.R # Check the output ...

  4. C语言访问MCU寄存器的两种方式

    转自http://blog.csdn.net/liming0931/article/details/7752248 单片机的特殊功能寄存器SFR,是SRAM地址已经确定的SRAM单元,在C语言环境下对 ...

  5. R语言—如何安装Github包的解决方法,亲测有效

    R语言—如何安装Github包的解决方法,亲测有效 准备安装材料: R包-REmap GitHub下载地址:https://github.com/lchiffon/REmap R包-baidumap ...

  6. php取得当前访问url文件名的几种方法

    php下获取当前访问的文件名的几种方法.推荐函数:一是PHP获取当前页面的网址: dedecms用的也是这个哦. <?php //获得当前的脚本网址 function GetCurUrl() { ...

  7. C语言清空输入缓冲区的N种方法对比

    转自C语言清空输入缓冲区的N种方法对比 C语言中有几个基本输入函数: //获取字符系列 int fgetc(FILE *stream); int getc(FILE *stream); int get ...

  8. struts2的action访问servlet API的三种方法

    学IT技术,就是要学习... 今天无聊看看struts2,发现struts2的action访问servlet API的三种方法: 1.Struts2提供的ActionContext类 Object g ...

  9. Action访问Servlet API的三种方法

    一.为什么要访问Servlet API ? Struts2的Action并未与Servlet API进行耦合,这是Struts2 的一个改良,从而方便了单独对Action进行测试.但是对于Web控制器 ...

随机推荐

  1. Ambari配置Hive,Hive的使用

    mysql安装,hive环境的搭建 ambari部署hadoop 博客大牛:董的博客 ambari使用 ambari官方文档 hadoop 2.0 详细配置教程 使用Ambari快速部署Hadoop大 ...

  2. Long类型转json时前端js丢失精度解决方案

    一.问题背景 Java后端开发过程中,尤其是id字段,因数值太大,通过json形式传输到前端后,在js解析时,会丢失精度. 如果对精度丢失没有什么概念,可以看一个知乎的帖子,来感受一下:https:/ ...

  3. POJ 1426 Find The Multiple(寻找倍数)

    POJ 1426 Find The Multiple(寻找倍数) Time Limit: 1000MS    Memory Limit: 65536K Description - 题目描述 Given ...

  4. File类文件的常见操作

    boolean exists() 判断文件或者目录是否存在 boolean isFile()  判断是否是文件 boolean isDirectory() 判断是否是目录 String getPath ...

  5. 当面试官问你GET和POST区别的时候,请这么回答.......

    文章内容转载于微信公众号WebTechGarden 一.GET和POST的'普通'区别 GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就 ...

  6. 跳跳虎回家(国庆10.1模拟赛T2)

    题目: [题目描述] 跳跳虎在外面出去玩忘了时间,现在他需要在最短的时间内赶回家. 跳跳虎所在的世界可以抽象成一个含有 n 个点的图(点编号从 1 到 n ),跳跳虎现在在 1 号点,跳跳虎的家在 n ...

  7. Python 模块(module)

    模块(module)也是为了同样的目的.在Python中,一个.py文件就构成一个模块.通过模块,你可以调用其它文件中的程序. first.py def laugh(): print "Ha ...

  8. jsp技术和el表达式和jstl技术

    注:本文参考黑马视频的讲义 jsp技术 1.jsp脚本 )<%java代码%> ----- 内部的java代码翻译到service方法的内部 )<%=java变量或表达式> - ...

  9. 学习笔记46—如何使Word和EndNote关联

    1)打开Word文件项目中的选项,然后点击加载项, 2)找到Endnote安装目录,选择目录中的Configure EndNote.exe,选中configuration endnote compon ...

  10. dock容器操作命令

    删除容器 docker rm -f ams 删除镜像 docker rmi -f ams:351 构建镜像 docker build -t ams:351 . 启动容器 docker run  --p ...