r - 使用包含匹配数字的向量从具有未知结构的混合类型列中提取数字
问题描述
我的 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
先感谢您!
解决方案
您可以使用正则表达式df2
在df
. 然后可以(懒惰地)将其包装在 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
定义如上(因为未指定用于其他数据帧的库)。
推荐阅读
- html - 从网页单击 Excel 图标的 VBA 代码 - 第 2 部分
- yii - flash 适用于 Session 但不适用于 DBsession
- java - 类“java.lang.ref.Finalizer”,由“加载”
",占用 6,125,536 (11.96%) 个字节 - catch2 - catch2:如何在测试用例中执行另一个进程?
- data-structures - 无法理解后缀函数的中缀
- html - 如何通过单击按钮 reactjs 创建一个新的输入字段行
- postgresql - 使用 Hasura 在 postgresql 中搜索 jsonb 字段
- python - Python Selenium 自动预订机器人
- scala - 如何在 sbt 项目中使用 slick 从 jar 中加载二进制 db 文件
- mongodb - Mongo Db 如何检测管道中的错误?