gpt4 book ai didi

r - 如何用R中的查找代码用字符串替换列

转载 作者:行者123 更新时间:2023-12-03 23:35:00 25 4
gpt4 key购买 nike

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

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

编辑:

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

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

EDIT 3 正如建议的那样,我为下一期提出了一个新问题: How to replace repeated strings and space in-between with look-up codes in R

最佳答案

我们可以使用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))

关于r - 如何用R中的查找代码用字符串替换列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60765697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com