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

问题描述 投票:1回答:2

我的spark tibble [spark_tbl1]中有一个混合类型列(字符串和具有不同结构的数字),可能包含每行的数字代码。我得到另一个tibble [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 

先感谢您!

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


0
投票

从Scala的角度来看,您需要相应地进行调整:

  1. 将你的tbl1分区为大数量的分区,df。
  2. 从tbl2创建一个List l。 val l = ...toList
  3. 以某种方式执行withColumn功能,例如 df.withColumn("some col", col("your col").rlike(l.mkString("|")) )
© www.soinside.com 2019 - 2024. All rights reserved.