如何在 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)