r - 匹配r中同一列中的两个名称
问题描述
我是在 R 中编码的新手,并且发现在同一列中匹配两个名称时遇到了麻烦。
更具体地说,我有一个多行表,其中有一列名为“fileName”,它给出了 persay 不同颜色的名称。该表由两个不同的表组合而成,因此第一个表的颜色名称称为 new_red,第二个称为 old_red。
我希望能够创建一个新列,说明如果字符集在 fileName 列中多次匹配,则在新列中为放置颜色的行写入“匹配”。如果 new_ 是一种独特的颜色,其中没有具有该颜色的 old_,写入“No_new_match”,对于旧的颜色,它会写入“No_old_match”。
我相信有一行代码在名称后引用了一定数量的数字/字符,即它会为 new_xxx 查找 3 个字符。我尝试以类似“new\d{3}”的方式进行操作,但它并没有按照我的预期工作。
这是我所指的一个例子
文件名
- 新红
- 新蓝
- 新绿
- 老红
- old_purple
匹配
No_new_match
No_new_match
匹配
无旧匹配
任何帮助将不胜感激,我知道如何为我想要制作的表格创建一个新列,但我在这部分遇到了麻烦。再次谢谢你!
解决方案
这是使用正则表达式的一种方法:
fileName <- c("new_red", "new_blue", "new_green", "old_red", "old_purple")
color <- gsub("(new_)|(old_)", "", fileName)
color.freq <- table(color)
df <- data.frame(
fileName = fileName,
color = color,
match = ifelse(
color.freq[color] == 2,
"Match",
ifelse(
grepl("new", fileName),
"No_new_match",
"No_old_match"
)
)
)
fileName color match
1 new_red red Match
2 new_blue blue No_new_match
3 new_green green No_new_match
4 old_red red Match
5 old_purple purple No_old_match
推荐阅读
- regex - Get the first character using Regex
- google-sheets - 我需要一个有多个条件的countif
- amazon-web-services - Powershell 写入 AWS S3
- reactjs - 为什么要在升级 Material UI 时升级 React
- mysql - 来自 MySQL 数据库的查询在 node.js 和 JSON.stringify() 中返回 [Object] [Object] 似乎不起作用
- docker - Docker如何将文件复制到Windows?
- python - 为什么 Best First search Python 实现没有给出正确的输出
- reactjs -
不显示反应中的组件 - c - 为什么我得到这个程序的错误输出?
- c# - 在 UAC OFF 的情况下在具有特权提升的子进程中启动 Windows 服务