【发布时间】:2017-01-28 06:19:02
【问题描述】:
我有两个数据框
df1
+-------+---------+
| Id | Title |
+-------+---------+
| 1 | AAA |
| 2 | BBB |
| 3 | CCC |
+-------+---------+
与
df2
+-------+---------------+------------------------------------+
| Id | Sub | Body |
+-------+---------------+------------------------------------+
| 1 | some sub1 | some mail body AAA some text here |
| 2 | some sub2 | some text here BBB continues here |
| 3 | some sub3 | some text AAA present here |
| 4 | some sub4 | AAA string is present here also |
| 5 | some sub5 | CCC string is present here |
+-------+---------------+------------------------------------+
我想将 df1 中的 Title 与 df2 的 Body 列匹配,
如果 Body 列中存在标题字符串,则应连接两行,输出数据框应如下所示:
df3
+----------+---------------+------------------------------------+
| Title | Sub | Body |
+----------+---------------+------------------------------------+
| AAA | some sub1 | some mail body AAA some text here |
| BBB | some sub2 | some text here BBB continues here |
| AAA | some sub3 | some text AAA present here |
| AAA | some sub4 | AAA string is present here also |
| CCC | some sub5 | CCC string is present here |
+----------+---------------+------------------------------------+
【问题讨论】:
-
我的回答对你有用吗?
-
@DAXaholic,感谢您的回复。您的示例与您的代码完美配合,但是当我尝试添加我的实际数据时,我收到以下错误。
Error in grepl(df1$title[idx], df2$body) : invalid 'pattern' argument。对不起,我在我的问题中又错过了一件事情,在 Title 我有像“AAA BB”这样的字符串,而不仅仅是“AAA”。我用数据“AAA BB”尝试了你的代码,它给出了以下错误Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 1, 0。 -
当我们不能假设每个标题都匹配某些行时,我用另一种方法更新了我的答案 - 希望有帮助