簡體   English   中英

R-識別部分部分字符串匹配的其余部分或查找列中的部分重復項

[英]R - Identifying the rest of a partial string match or finding partial duplicates within a column

我想基於“樣本”產生“重復”列。 003是樣本ID,003r是同一樣本的副本。 “樣品”列中的復制樣品名稱的前三個字符相同。

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但無法以給我想要的結果的方式將它們組合在一起,因此我被困在這一點上。 感謝您的幫助,謝謝。

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM