【问题标题】:R - Identifying the rest of a partial string match or finding partial duplicates within a columnR - 识别部分字符串匹配的其余部分或在列中查找部分重复项
【发布时间】:2017-03-13 00:26:11
【问题描述】:

我想根据“示例”生成“重复”列。 003 是样品 ID,003r 是同一样品的复制品。 “Sample”列中的重复样本名称的前 3 个字符相同。

Sample <- c("001","002","003","003r","004","005","005r")
Value <- c(2,5,4,4,5,6,7)
Duplicate <- c(F,F,T,T,F,T,T)
df <- data.frame(Sample,Value,Duplicate)
df

  Sample Value Duplicate
1    001     2     FALSE
2    002     5     FALSE
3    003     4      TRUE
4   003r     4      TRUE
5    004     5     FALSE
6    005     6      TRUE
7   005r     7      TRUE

我正在尝试使用ifelsegrep,但无法以给我想要的结果的方式组合它们,我被困在这一点上。 非常感谢您的帮助,谢谢。

【问题讨论】:

  • 你能多说一下数据吗:你感兴趣的总是前3个字符吗?您要检查重复的部分是否总是数字和变体字符?
  • 您可以尝试stringdist::stringdistmatrix(df$Sample),但不清楚为什么003r003 是骗子,而001002 却不是——这两对都只有一个字符距离。如果您要寻找的只是匹配前 3 个字符,您可以简单地执行 duplicated(substring(df$Sample, 1, 3)) | duplicated(substring(df$Sample, 1, 3), fromLast = TRUE),它会提供您想要的输出。
  • @DavidArenburg 非常感谢,这就是我一直在寻找的东西,过了一会儿我也明白了它是如何工作的。

标签: r regex


【解决方案1】:

@David Arenburg 是对的,您需要首先正式定义“部分匹配”名称的含义。假设部分匹配是由示例中子字符串的位置 1(开始)和 3(停止)之间的完全匹配(相同)定义的,我们可以创建一个包含此子字符串的新列:

df$sample_substr <- substr(df$Sample,start = 1,stop = 3)

... 然后简单地计算每个 sample_substr 的出现次数(频率)。我建议为此使用“plyr”包(非常快):

library(plyr)
# group by 'sample_substr' and count the number of occurrences
df <- ddply(df, .(sample_substr), mutate, frequency=length(sample_substr))
# if frequency is 1, it is unique, i.e. not a duplicate. If frequency is > 1, it is not unique, i.e. a duplicate.
df$Dup <- ifelse(df$frequency==1, FALSE, TRUE)
# test if our definition of Dup holds the same value as yours in Duplicate
df$Dup==df$Duplicate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多