【问题标题】:apply if else mutate function on all columns of a spark dataframe in sparklyr在 sparklyr 中的 spark 数据帧的所有列上应用 if else mutate 函数
【发布时间】:2021-09-23 01:59:33
【问题描述】:

如何在 sparklyr 的 spark 数据帧的所有列上应用 if else mutate 函数?例如,假设我想将 iris 数据帧中小于 2 的所有值转换为 0。在 sparklyr 之外,有很多方法可以做到这一点,但是使用 sparklyr 这似乎有点复杂。我使用以下自定义函数尝试了一种方法:

iris_sdf <- sdf_copy_to(sc, iris, overwrite = TRUE)
iris_num_sdf <- iris_sdf %>% select(-Species)

recode_val <- function(x) ifelse(x < 2, 0, x)

iris_num_sdf %>% mutate_all(funs(recode_val))

但出现错误This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 7 Error : org.apache.spark.sql.AnalysisException:

我使用spark_apply 尝试了以下操作,但得到了无意义的结果。

iris_num_sdf %>% 
  spark_apply(recode_val, context = {colName <- colnames(iris_num_sdf)})

我也在下面尝试了这个,这似乎可以解决问题,但我希望有更优雅的东西。

convert_x <- function(col){
  col <- sym(col)
  iris_num_sdf %>% mutate({{col}} := ifelse({{col}} < 2, 0, {{col}})) %>% select({{col}})
}

col_list <- colnames(iris_num_sdf)
out <- lapply(col_list, convert_x)

do.call(sdf_bind_cols, out)

【问题讨论】:

  • 你能在 sparklyr 中使用purrr 之类的map_df 等函数吗?
  • @RonakShah 是的purrr 功能可用

标签: r apache-spark dplyr sparklyr


【解决方案1】:

你可以试试这个方法-

library(dplyr)

convert_x <- function(col){
  iris_num_sdf %>% transmute({{col}} := ifelse(.data[[col]] < 2, 0,.data[[col]]))
}

col_list <- colnames(iris_num_sdf)
result <- purrr::map_dfc(col_list, convert_x)

基本 R 选项 -

recode_val <- function(x) ifelse(x < 2, 0, x)
out <- do.call(rbind, lapply(iris_num_sdf, recode_val))

【讨论】:

  • 谢谢,显然只有少数 purrr 函数有效,而 map_dfc 不是其中之一。
  • 我不知道哪些有效,哪些无效,但如果您可以使用result &lt;- purrr::map(col_list, convert_x) %&gt;% bind_cols(),则其工作方式相同。
  • 奇怪的是仍然无法正常工作,我知道地图适用于 sparklyr,但我不清楚在什么条件下。
  • 我用基本 R 选项更新了答案。让我知道这是否有效。
  • 谢谢,不幸的是,base r 方法不适用于 sparklyr。
猜你喜欢
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2018-01-19
  • 2020-12-30
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
相关资源
最近更新 更多