首页 > 解决方案 > 匹配r中同一列中的两个名称

问题描述

我是在 R 中编码的新手,并且发现在同一列中匹配两个名称时遇到了麻烦。

更具体地说,我有一个多行表,其中有一列名为“fileName”,它给出了 persay 不同颜色的名称。该表由两个不同的表组合而成,因此第一个表的颜色名称称为 new_red,第二个称为 old_red。

我希望能够创建一个新列,说明如果字符集在 fileName 列中多次匹配,则在新列中为放置颜色的行写入“匹配”。如果 new_ 是一种独特的颜色,其中没有具有该颜色的 old_,写入“No_new_match”,对于旧的颜色,它会写入“No_old_match”。

我相信有一行代码在名称后引用了一定数量的数字/字符,即它会为 new_xxx 查找 3 个字符。我尝试以类似“new\d{3}”的方式进行操作,但它并没有按照我的预期工作。

这是我所指的一个例子

文件名

  1. 新红
  2. 新蓝
  3. 新绿
  4. 老红
  5. old_purple

  1. 匹配

  2. No_new_match

  3. No_new_match

  4. 匹配

  5. 无旧匹配

    任何帮助将不胜感激,我知道如何为我想要制作的表格创建一个新列,但我在这部分遇到了麻烦。再次谢谢你!

标签: rdplyr

解决方案


这是使用正则表达式的一种方法:

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

推荐阅读