【问题标题】:Gather in sparklyr聚集在 sparklyr
【发布时间】:2018-11-01 02:04:57
【问题描述】:

我正在使用 sparklyr 来处理一些数据。 给定一个,

a<-tibble(id = rep(c(1,10), each = 10),
          attribute1 = rep(c("This", "That", 'These', 'Those', "The", "Other", "Test", "End", "Start", 'Beginning'), 2),
          value = rep(seq(10,100, by = 10),2),
          average = rep(c(50,100),each = 10),
          upper_bound = rep(c(80, 130), each =10),
          lower_bound = rep(c(20, 70), each =10))

我想使用“收集”来操作数据,如下所示:

b<- a %>% 
     gather(key = type_data, value = value_data, -c(id:attribute1))

但是,“聚集”在 sparklyr 上不可用。我见过一些人使用 sdf_pivot 来模仿“聚集”(例如How to use sdf_pivot() in sparklyr and concatenate strings?),但我不知道在这种情况下如何使用它。

有人有想法吗?

干杯!

【问题讨论】:

  • 你不能安装额外的包?只是为了好奇。
  • 我可以安装另一个包,如果它具有完成这项工作的功能。我尝试使用包回复器,在这篇文章 (win-vector.com/blog/2017/07/…) 中,据说它有一个函数,replyr_moveValuesToRows(),它应该以它的工作方式模拟收集。但是,我安装包后无法使用 find 这个功能,并且它不在参考手册中。

标签: r apache-spark dplyr sparklyr


【解决方案1】:

这是一个在 sparklyr 中模仿 gather 的函数。这将收集给定的列,同时保持其他所有内容不变,但如果需要,它可以轻松扩展。

# Function
sdf_gather <- function(tbl, gather_cols){

  other_cols <- colnames(tbl)[!colnames(tbl) %in% gather_cols]

  lapply(gather_cols, function(col_nm){
    tbl %>% 
      select(c(other_cols, col_nm)) %>% 
      mutate(key = col_nm) %>%
      rename(value = col_nm)  
  }) %>% 
    sdf_bind_rows() %>% 
    select(c(other_cols, 'key', 'value'))
}

# Example
spark_df %>% 
  select(col_1, col_2, col_3, col_4) %>% 
  sdf_gather(c('col_3', 'col_4'))

【讨论】:

    【解决方案2】:

    您可以使用map / explode 设计一个等效项:

    sdf_gather <- function(data, key = "key", value = "value", ...) {
      cols <- list(...) %>% unlist()
    
      # Explode with map (same as stack) requires multiple aliases so
      # dplyr mutate won't work for us here.
      expr <- list(paste(
        "explode(map(",
        paste("'", cols, "',`",  cols, "`", sep = "", collapse = ","),
        ")) as (", key, ",", value, ")", sep = ""))
    
      keys <- data %>% colnames() %>% setdiff(cols) %>% as.list()
    
      data %>%
        spark_dataframe() %>% 
        sparklyr::invoke("selectExpr", c(keys, expr)) %>% 
        sdf_register()
    }
    

    或 Hive stack function:

    sdf_gather <- function(data, key = "key", value = "value", ...) {
      cols <- list(...) %>% unlist()
      expr <- list(paste(
        "stack(", length(cols), ", ",
        paste("'", cols, "',`",  cols, "`", sep="", collapse=","),
        ") as (", key, ",", value, ")", sep=""))
    
      keys <- data %>% colnames() %>% setdiff(cols) %>% as.list()
    
      data %>%
        spark_dataframe() %>% 
        sparklyr::invoke("selectExpr", c(keys, expr)) %>% 
        sdf_register()
    }
    

    两者应该给出相同的结果:

    long <- sdf_gather(
      df, "my_key", "my_value",
      "value", "average", "upper_bound", "lower_bound")
    long
    
    # Source:   table<sparklyr_tmp_7b8f5989ba4d> [?? x 4]
    # Database: spark_connection
          id attribute1 my_key      my_value
       <dbl> <chr>      <chr>          <dbl>
     1     1 This       value             10
     2     1 This       average           50
     3     1 This       upper_bound       80
     4     1 This       lower_bound       20
     5     1 That       value             20
     6     1 That       average           50
     7     1 That       upper_bound       80
     8     1 That       lower_bound       20
     9     1 These      value             30
    10     1 These      average           50
    # ... with more rows
    

    并且可以进行修改以支持非标准评估。

    请注意,这两种方法都需要同类列类型。

    备注

    explode 版本生成以下查询:

    SELECT id, attribute1, 
           explode(map(
             'value', `value`,
             'average', `average`,
             'upper_bound', `upper_bound`,
             'lower_bound', `lower_bound`)) as (my_key,my_value)
    
    FROM df
    

    和optimized logical execution plan

    org.apache.spark.sql.catalyst.plans.logical.Generate
    Generate explode(map(value, value#16, average, average#17, upper_bound, upper_bound#18, lower_bound, lower_bound#19)), [2, 3, 4, 5], false, [my_key#226, my_value#227]
    +- InMemoryRelation [id#14, attribute1#15, value#16, average#17, upper_bound#18, lower_bound#19], StorageLevel(disk, memory, deserialized, 1 replicas)
          +- Scan ExistingRDD[id#14,attribute1#15,value#16,average#17,upper_bound#18,lower_bound#19]
    

    stack 版本生成时

    SELECT id, attribute1, 
           stack(4, 
                 'value', `value`,
                 'average', `average`,
                 'upper_bound', `upper_bound`,
                 'lower_bound', `lower_bound`) as (my_key,my_value)
    FROM df
    

    和

    org.apache.spark.sql.catalyst.plans.logical.Generate
    Generate stack(4, value, value#16, average, average#17, upper_bound, upper_bound#18, lower_bound, lower_bound#19), [2, 3, 4, 5], false, [my_key#323, my_value#324]
    +- InMemoryRelation [id#14, attribute1#15, value#16, average#17, upper_bound#18, lower_bound#19], StorageLevel(disk, memory, deserialized, 1 replicas)
          +- Scan ExistingRDD[id#14,attribute1#15,value#16,average#17,upper_bound#18,lower_bound#19]
    

    在生成的 SQL 中,单引号值(即'value')是文字字符串,而反引号值表示列引用。

    【讨论】:

      【解决方案3】:

      不,没有pivot 在这里回答。

      我也在等待更好的。

      library(sparklyr)
      library(rlang)
      library(dplyr)
      
      #Given
      sparkDf_a <- copy_to(dest = sc, df = a)
      
      helper_fn <- function(df, key, val, ...){
      
          quo_col <- enquo(val)
      
          df %>% 
              dplyr::group_by(id, attribute1) %>% 
              dplyr::select(!!quo_col) %>% 
              mutate(type_data  = key, 
                     value_data = !!quo_col) %>% 
              dplyr::select(-!!quo_col)
      }
      
      b <- sdf_bind_rows(
            helper_fn(df = sparkDf_a, key = 'value', val = value),
            helper_fn(df = sparkDf_a, key = 'average', val = average),
            helper_fn(df = sparkDf_a, key = 'upper_bound', val = upper_bound),
            helper_fn(df = sparkDf_a, key = 'lower_bound', val = lower_bound)
       )
      

      结果

      collect(b)
      # A tibble: 80 x 4
      # Groups:   id, attribute1 [20]
            id attribute1   type_data value_data
         <dbl>      <chr>       <chr>      <dbl>
       1     1        End upper_bound         80
       2     1      Other lower_bound         20
       3     1      Start lower_bound         20
       4     1       Test     average         50
       5     1       Test upper_bound         80
       6     1       That     average         50
       7     1       That lower_bound         20
       8     1      Those       value         40
       9    10      Start lower_bound         70
      10    10       That     average        100
      # ... with 70 more rows
      

      【讨论】:

        猜你喜欢
        • 2021-01-15
        • 2017-10-19
        • 2018-10-03
        • 2017-08-21
        • 2017-07-02
        • 2017-02-07
        • 2017-11-20
        • 2017-07-14
        • 2017-09-18
        相关资源
        最近更新 更多