使用包含匹配数字的向量从结构未知的混合类型列中提取数字

时间:2019-03-24 15:14:21

标签: r dplyr sparklyr

我的火花[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 

提前谢谢!

2 个答案:

答案 0 :(得分:0)

从Scala角度来看,在功能上,因此您需要进行相应的调整:

  1. 将tbl1划分为大型分区df。
  2. 从tbl2创建列表l。

    val l = ...toList
    
  3. 以某种方式执行withColumn函数,例如

    df.withColumn("some col",
                   col("your col").rlike(l.mkString("|"))
                 )
    

答案 1 :(得分:0)

您可以使用正则表达式为df2中的每个数字代码找到df中的相应行。然后,可能(懒洋洋地)将其包装在lapply中以遍历行(这里可能有更聪明的方法),例如

 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的定义如上(因为未指定用于其他数据帧的库)。