【问题标题】:sparklyr can't filter missing value of `sd` on single valuesparklyr 无法在单个值上过滤 `sd` 的缺失值
【发布时间】:2017-12-19 20:43:25
【问题描述】:

sd() 应用于 spark 数据帧中的单个值(通过 R 中的 sparklyr 包)会导致缺失值,由于它是缺失值而无法过滤掉。

有人可以解释这个/提供一个好的解决方案吗?

以下示例。


library(sparklyr)
library(dplyr)

sc <- spark_connect(master = "local")
#> * Using Spark: 2.1.0

x <- data.frame(grp = c("a", "a", "c"), x = c(1, 2, 3))

copy_to(sc, x, "tmp", overwrite = TRUE)
#> # Source:   table<tmp> [?? x 2]
#> # Database: spark_connection
#>     grp     x
#>   <chr> <dbl>
#> 1     a     1
#> 2     a     2
#> 3     c     3

x_tbl <- tbl(sc, "tmp") %>% group_by(grp) %>% mutate(x_sd = sd(x))

x_tbl
#> # Source:   lazy query [?? x 3]
#> # Database: spark_connection
#> # Groups:   grp
#>     grp     x      x_sd
#>   <chr> <dbl>     <dbl>
#> 1     a     1 0.7071068
#> 2     a     2 0.7071068
#> 3     c     3       NaN

x_tbl %>% filter(!is.na(x_sd)) %>% collect()
#> # A tibble: 3 x 3
#> # Groups:   grp [2]
#>     grp     x      x_sd
#>   <chr> <dbl>     <dbl>
#> 1     a     1 0.7071068
#> 2     a     2 0.7071068
#> 3     c     3       NaN

【问题讨论】:

    标签: r apache-spark dplyr sparklyr


    【解决方案1】:

    这是sparklyr 和Spark 之间不兼容的问题。在 Spark 中有 NULLS(有点相当于 R NA)和 NaNs,每个都有不同的处理规则,但在 sparklyr 中,这两个值都被提取为 NaN

    要过滤掉NaN,您必须使用isnan(不要将其与R is.nan混淆):

    x_tbl %>% filter(!isnan(x_sd)) %>% collect()
    
    # A tibble: 2 x 3
    # Groups:   grp [1]
        grp     x      x_sd
      <chr> <dbl>     <dbl>
    1     a     1 0.7071068
    2     a     2 0.7071068
    

    为了更好地说明问题:

    df <- copy_to(sc,
      data.frame(x = c("1", "NaN", "")), "df", overwrite = TRUE
    ) %>% mutate(x = as.double(x))
    
    df %>% mutate_all(funs(isnull, isnan)) 
    
    # Source:   lazy query [?? x 3]
    # Database: spark_connection
          x isnull isnan
      <dbl>  <lgl> <lgl> 
    1     1  FALSE FALSE
    2   NaN  FALSE  TRUE
    3   NaN   TRUE FALSE
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2018-01-24
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多