【问题标题】:Find size of intersection of two list-columns in sparklyr在 sparklyr 中查找两个列表列的交集大小
【发布时间】:2022-06-15 18:21:10
【问题描述】:

我正在使用 sparklyr 中的 tbl_spark。

我有一个带有两个列表类型列的 spark Dataframe,我想输出两件事:

  1. 两个列表的交集(作为一个列表)
  2. 交叉点的元素个数

我的输入数据如下所示(使用 mtcars 数据集),其中“sc”是我的 spark 连接:

library(dplyr)      
library(sparklyr)

## Load mtcars into spark with connection "sc"
mtcars_spark <- copy_to(sc, mtcars)

## Wrangle mtcars to get list columns using ft_regex_tokenizer()
tbl_with_lists <- mtcars_spark %>%
  mutate(mpg_rounded = round(mpg, -1)) %>%
  group_by(mpg_rounded) %>%
    summarize(
      cyl_all = paste(collect_set(as.character(cyl)), sep = ", "),
      gear_all = paste(collect_set(as.character(gear)), sep = ", ")
    ) %>%
  ungroup() %>%
  ft_regex_tokenizer("cyl_all", "cyl_list", pattern = "[,]\\s*") %>%
  ft_regex_tokenizer("gear_all", "gear_list", pattern = "[,]\\s*")

tbl_with_lists

## # Source: spark<?> [?? x 5]
##   mpg_rounded cyl_all       gear_all      cyl_list   gear_list 
##         <dbl> <chr>         <chr>         <list>     <list>    
## 1          10 8.0           3.0           <list [1]> <list [1]>
## 2          30 4.0           5.0, 4.0      <list [1]> <list [2]>
## 3          20 8.0, 6.0, 4.0 5.0, 3.0, 4.0 <list [3]> <list [3]>

我在找出如何做到这一点方面没有取得多大成功。有什么想法吗?

【问题讨论】:

  • 你能提供list1和list2作为dput()吗?
  • 我不确定你所说的 dput 是什么意思?这不是我以前遇到过的功能
  • 请参阅here,了解如何创建最小可重复性示例。它将通过提供最少的代码(即list1 和list2 的数据)来帮助其他人。尝试运行dput(mtcars) 看看它是如何工作的。如果 mtcars 是 list1,您可以复制/粘贴输出以在您的问题中提供。
  • 原始帖子已编辑以包含与 mtcars 的明确表示 - 这有帮助吗?我想知道是否有一种方法可以改变两个列表列(cyl_list 和 gear_list)以产生 1)具有交叉点的新列和 2)具有交叉点大小的新列

标签: r sparklyr


【解决方案1】:

我发现使用explode() 可能是一种解决方法。

如果有更直接的方法会更好吗?不确定此解决方案能否扩展到更大的数据集。

tbl_with_lists %>%
  ## First explode the lists to create new rows for each unique list value
  mutate(
    cyl_explode  = explode(cyl_list)
  ) %>%
  mutate(
    gear_explode = explode(gear_list)
  ) %>%

  ## Summarize to count number of matches - this gives the size of the intersection of the two lists
  group_by(mpg_rounded, cyl_all, gear_all) %>%
  summarize(size_of_intersection = sum(as.integer(cyl_explode == gear_explode)))


## Output:
##
## # Source: spark<?> [?? x 4]
## # Groups: mpg_rounded, cyl_all
##   mpg_rounded cyl_all       gear_all      size_of_intersection
##         <dbl> <chr>         <chr>                        <dbl>
## 1          10 8.0           3.0                              0
## 2          30 4.0           5.0, 4.0                         1
## 3          20 8.0, 6.0, 4.0 5.0, 3.0, 4.0                    1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-13
    • 2013-10-12
    • 2021-03-18
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多