r - 如何用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),因此非常感谢任何快速的解决方案。请注意,此字符串长度并不总是相同的......例如,在一行中我可以有字符串a
to d
,在其他a
to 中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
编辑 3正如建议的那样,我为下一个问题打开了一个新问题: 如何用 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))
推荐阅读
- javascript - 将纬度和经度值转换为地名并显示?
- azure - 如何通过 Graph API 从 MS Teams 中恢复通话记录信息
- angular - 如何使用从 HttpClient (Angular) 获得的数据进行排序创建 mat-table
- python - 为什么列表列表的 zip() 会输出这样的结果?
- angular - 如何使用 Prime NG 在条件下选择单选按钮
- amazon-web-services - AWS S3 - java.net.UnknownHostException:repo-user-bucket.s3.us-west-2.amazonaws.com
- ssh - gcp 上的远程执行配置程序未与主机连接
- xaml - 更新 Badge、Xamarin Forms 应用程序中的计数器
- json - Postgres Json_each_Text() 函数
- python - 带有元素的 Python 列表操作