首页 > 解决方案 > 如何用R中的查找代码用字符串替换列

问题描述

想象一下,我有一个带有字符串列的数据框或数据表,其中一行如下所示:

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),因此非常感谢任何快速的解决方案。请注意,此字符串长度并不总是相同的......例如,在一行中我可以有字符串ato d,在其他ato 中f

编辑

我们得到了上述情况的解决方案,但是想象一下我有一个这样的字符串:

a; b: peter, joe smith, john smith; c: luke, james, john smith

如何替换这些john smith根据是否属于bc类别可以具有两个不同代码的已知?此外,字符串可以包含在它们之间有空格的单词。

编辑 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

编辑 3正如建议的那样,我为下一个问题打开了一个新问题: 如何用 R 中的查找代码替换重复的字符串和中间空格

标签: rdataframedata.tablestr-replacegsub

解决方案


我们可以用gsubfn

library(gsubfn)
gsubfn("([a-z]\\d+)", setNames(as.list(df1$code), df1$string), str1)
#[1] "10; b: 20, 30, 40; c: 50, 60, 70; d: 80, 90, 100, 110"

对于编辑版本

gsubfn("(\\w+ ?\\w+?)",  setNames(as.list(df2$code), df2$string), str2)
#[1] "a; b: 20, 30, 40; c: 50, 60, 40"

数据

str1 <- "a1; b: b1, b2, b3; c: c1, c2, c3; d: d1, d2, d3, d4"
df1 <- structure(list(string = c("a1", "b1", "b2", "b3", "c1", "c2", 
 "c3", "d1", "d2", "d3", "d4"), code = c(10L, 20L, 30L, 40L, 50L, 
 60L, 70L, 80L, 90L, 100L, 110L)), class = "data.frame",
  row.names = c(NA, -11L))

str2 <- "a; b: peter, joe smith, john smith; c: luke, james, john smith"

df2 <- structure(list(string = c("a", "peter", "joe smith", "john smith", 
"luke", "james", "john smith"), code = c(10L, 20L, 30L, 40L, 
50L, 60L, 70L)), class = "data.frame", row.names = c(NA, -7L))

推荐阅读