2017-10-24 22 views
0

2つの識別子(グループとID)でグループ化された大きなデータと、最初の期間に表示されるInitial列と、Postの列期間。作業実施例以下である:唯一の新しい要素が存在する場合、および既存と新規の両方の要素が存在する場合2つの文字列の要素の部分一致R

SampleDF<-data.frame(Group=c(0,0,1),ID=c(2,2,3), 
Initial=c('F28D,G06F','F24J ,'G01N'), 
Post=c('G06F','H02G','F23C,H02G,G01N')) 

私は、要素が一致したときに見つけるために、各Group/ID組み合わせに対してInitialPostの要素を比較したいです。 1があることを示し、

SampleDF<-cbind(SampleDF, 'Type'=rbind(0,1,2)) 

(相対Initialに)0Postに新しい要素(複数可)が存在しないことを示している。理想的には、私は、次の出力を有する新しいType変数で終わるしたいですPostの新しい要素のみ、2は、Postに既存の要素と新しい要素の両方が存在することを示します。

+0

入力に '' '' '' ' – rsmith54

答えて

1

agreplを使用して文字列照合を行っている間にpatternvectorが異なるため、状況は複雑です。だから、ここで私は非常にトリッキーですが、非常にうまくやっている解決策を考え出します。

element_counter = list() 
for (i in 1:length(SampleDF$Initial)) { 
    if (length(strsplit(as.character(SampleDF$Initial[i]), ",")[[1]]) > 1) { 
    element_counter[[i]] <- length(as.character(SampleDF$Post[i])) - sum(agrepl(as.character(SampleDF$Post[i]),strsplit(as.character(SampleDF$Initial[i]), ",")[[1]])) 
    } else { 
    element_counter[[i]] <- length(strsplit(as.character(SampleDF$Post[i]), ",")[[1]]) - sum(agrepl(SampleDF$Initial[i], strsplit(as.character(SampleDF$Post[i]), ",")[[1]])) 
    } 
} 

SampleDF$Type <- unlist(element_counter) 


## SampleDF 
# Group ID Initial    Post Type 
#1  0 2 F28D,G06F    G06F 0 
#2  0 2  F24J    H02G 1 
#3  1 3  G01N F23C,H02G,G01N 2 
1

私は、新しい値を持つ行を見つけ、2つのステップにプロセスを分割して、のみ新しい値を持つ行を見つけます。これらの2つの論理ベクトルを一緒に追加すると、型が作成されます。唯一の注意点は、型定義があなたの質問定義と少し違うということです。 0は新しい尺度がないことを示し、1は新規かつ既存の尺度があることを示し、2は既存の尺度のみが存在することを示します。

# This approach needs character columns not strings, so stringsAsFactors = FALSE 
SampleDF<-data.frame(Group=c(0,0,1),ID=c(2,2,3), 
        Initial=c('F28D,G06F','F24J' ,'G01N'), 
           Post=c('G06F','H02G','F23C,H02G,G01N'), 
        stringsAsFactors = FALSE) 

# Identify rows where there are new occurrences in Post that are not present in Initial 
SampleDF$anyNewOccurrences <- 
    mapply(FUN = function(pattern, x){ 
    any(!grepl(pattern, x))}, 
    pattern = gsub("," , "|", SampleDF$Initial), 
    x = strsplit(SampleDF$Post, ",")) 

# Identify rows where there are only new occurences (no repeated values from Initial) 
SampleDF$onlyNewOccurrences <- 
    mapply(FUN = function(pattern, x){ 
    all(!grepl(pattern, x))}, 
    pattern = gsub("," , "|", SampleDF$Initial), 
    x = strsplit(SampleDF$Post, ",")) 

# Add the two value to gether to create a type code 
SampleDF$Type <- SampleDF$onlyNewOccurrences + SampleDF$anyNewOccurrences 
関連する問題