r - 在 sparklyr 中的 spark 数据帧的所有列上应用 if else mutate 函数
问题描述
如何在 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)
解决方案
您可以尝试这种方法 -
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))
推荐阅读
- python - 在 HTML 上托管 pygame 应用程序的最有效/最有效的方法是什么?
- python - 为什么 sentence.strip() 从这个字符串的末尾删除某些字符而不是其他字符?
- javascript - 如何在不改变宽度的情况下最小化条之间的间隙
- augmented-reality - 持久性保存的户外 ARKit 场景
- laravel - Laravel - 删除父级时如何删除子行?
- angular - 确认密码 mat-error - Angular / Material
- c# - 操作在 Azure Cognitive 上返回了无效状态代码“未授权”
- python - 使用 spark 读取数据时错误的数据类型
- solr - Solr 主从复制 - 调用“详细信息”方法在主复制时出现异常
- html - 删除导航栏和图像之间的间距