首页 > 解决方案 > 使用包含匹配数字的向量从具有未知结构的混合类型列中提取数字

问题描述

我的 spark tibble [spark_tbl1] 中有一个混合类型列(具有不同结构的字符串和数字),它可能包含每一行的数字代码。我得到了另一个小标题 [spark_tbl2],它实际上列出了我想从 [spark_tbl1] 中提取的数字代码(大约 6000 行)。

问题是这两个小标题没有任何共同的键。什么是解决这个问题的聪明方法。下面是一个例子:

#This is my spark_tbl1 which contains the mmixed types column
#I limit rows to 3 (I got actually 1.6E6 rows)

df=data.frame(mixed_types_colum=c("ZB0R2298000","BZRT929700","FTUI06970T"),
                another_column=c("Banana","Apple","Orange"))
spark_tbl1=sdf_copy_to(sc,df,"df1",overwrite = TRUE)
spark_tbl1%>%head()
# Source: spark<spark_tbl1> [?? x 2]
  mixed_types_colum another_column
  <chr>             <chr>         
1 ZB0R2298000        Banana        
2 BZRT929700         Apple         
3 FTUI06970T        Orange  

#This tibble is supposed to have more than 6000 rows.
df2=data.frame(digit_code=c("298","297","697"))
spark_tbl2=sdf_copy_to(sc,df2,"df2",overwrite = TRUE)
spark_tbl2%>%head()
# Source: spark<spark_tbl2> [?? x 1]
  digit_code
  <chr>     
1 298       
2 297       
3 697     

我期望输出:

spark_tbl2%>%head()
# Source: spark<spark_tbl2> [?? x 3]
  mixed_types_colum another_column digit_code
  <chr>             <chr>          <chr>     
1 ZB0R2298000       Banana         298       
2 BZRT929700        Apple          297       
3 FTUI06970T        Orange         697 

先感谢您!

标签: rdplyrsparklyr

解决方案


您可以使用正则表达式df2df. 然后可以(懒惰地)将其包装在 alapply中以迭代行(这里可能有更聪明的方法),例如

 do.call(rbind, lapply(1:nrow(df2), 
                       function(k) cbind(df[grep(df2$digit_code[k], df$mixed_types_colum),], 
                                         df2$digit_code[k])
                 )
         )
# output
#   mixed_types_colum another_column df2$digit_code[k]
# 1       ZB0R2298000         Banana               298
# 2        BZRT929700          Apple               297
# 3        FTUI06970T         Orange               697

其中df,df2定义如上(因为未指定用于其他数据帧的库)。


推荐阅读