【问题标题】:How to pass variables to functions called in spark_apply()?如何将变量传递给 spark_apply() 中调用的函数?
【发布时间】:2018-03-03 03:50:05
【问题描述】:

我希望能够将额外的变量传递给 sparklyr 中 spark_apply 调用的函数。

例如:

# setup
library(sparklyr)
sc <- spark_connect(master='local', packages=TRUE)
iris2 <- iris[,1:(ncol(iris) - 1)]
df1 <- sdf_copy_to(sc, iris2, repartition=5, overwrite=T)

# This works fine
res <- spark_apply(df1, function(x) kmeans(x, 3)$centers)

# This does not
k <- 3
res <- spark_apply(df1, function(x) kmeans(x, k)$centers)

作为一个丑陋的解决方法,我可以通过将值保存到 R 包中然后引用它们来做我想做的事情。即

> myPackage::k_equals_three == 3
[1] TRUE

# This also works
res <- spark_apply(df1, function(x) kmeans(x, myPackage::k_equals_three)$centers)

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: r apache-spark sparklyr


    【解决方案1】:

    我没有设置 spark 来测试,但你能创建一个闭包吗?

    kmeanswithk <- function(k) {force(k); function(x) kmeans(x, k)$centers})
    k <- 3
    res <- spark_apply(df1, kmeanswithk(k))
    

    基本上只是创建一个函数来返回一个函数然后使用它。

    【讨论】:

      【解决方案2】:

      spark_apply() 现在有一个 context 参数供您将其他对象/变量/等传递给环境。

      res <- spark_apply(df1, function(x, k) {
        kmeans(x, k)$cluster},
        context = {k <- 3})
      

      k <- 3
      res <- spark_apply(df1, function(x, k) {
        kmeans(x, k)$cluster},
        context = {k})
      

      R 文档不包含任何带有上下文参数的示例,但您可以通过阅读 PR:https://github.com/rstudio/sparklyr/pull/1107 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2016-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        • 2019-12-06
        • 2017-10-03
        • 1970-01-01
        • 2018-11-10
        相关资源
        最近更新 更多