【发布时间】:2020-03-19 22:01:02
【问题描述】:
想象一下,我有一个带有字符串列的数据框或数据表,其中一行如下所示:
a1; b: b1, b2, b3; c: c1, c2, c3; d: d1, d2, d3, d4
还有一个查找表,其中包含用于映射每个字符串的代码。例如:
string code
a1 10
b1 20
b2 30
b3 40
c1 50
c2 60
...
我想要一个将这个字符串映射到代码的映射函数:
10; b: 20, 30, 40; c: 50, 60, 70; d: 80, 90, 100
我在 data.table/data.frame 中有一列这些字符串(超过 100k),因此非常感谢任何快速的解决方案。
请注意,此字符串长度并不总是相同的...例如,在一行中我可以有字符串a 到d,在其他a 到f。
编辑:
我们得到了上述情况的解决方案,但是想象一下我有一个这样的字符串:
a; b: peter, joe smith, john smith; c: luke, james, john smith
如何替换这些已知john smith 可以有两个不同的代码,具体取决于它属于b 还是c 类别?
此外,字符串可以包含单词,它们之间有空格。
编辑 2:
string code
a 10
peter 20
joe smith 30
john smith 40
luke 50
james 60
john smith 70
...
最终的解决方案是:
10; b: 20, 30, 40; c: 50, 60, 70
EDIT 3 正如建议的那样,我为下一期提出了一个新问题: How to replace repeated strings and space in-between with look-up codes in R
【问题讨论】:
-
lookup函数来自epicalc包可能会满足您的需求 -
新数据的预期输出是什么
-
@akrun 请参阅编辑 2。
标签: r dataframe data.table str-replace gsub