【问题标题】:Partial matching of elements in two string columns in RR中两个字符串列中元素的部分匹配
【发布时间】:2017-10-24 11:27:33
【问题描述】:

我有一个按两个标识符(组和 ID)分组的大型数据,Initial 列显示在初始时间段,Post 列显示在初始时间段之后发生的元素。下面是一个工作示例:

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 中的元素,以找出元素何时匹配、何时仅存在新元素以及何时同时存在预先存在的元素和新元素。理想情况下,我希望得到一个新的Type 变量,输出如下:

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

其中(相对于Initial0表示Post中没有新元素,1表示Post中只有新元素,@987654334 @ 表示Post 中既有已有元素也有新元素。

【问题讨论】:

  • 输入缺少 ``` '```

标签: r string match strsplit


【解决方案1】:

您的情况很复杂,因为您的patternvector 在使用agrepl 进行字符串匹配时会发生变化。所以,在这里我想出了一个非常棘手但做得很好的解决方案。

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

【讨论】:

    【解决方案2】:

    我将过程分为两个步骤,查找具有新值的行,然后查找具有only 新值的行。将这两个逻辑向量加在一起将创建类型。唯一需要注意的是,类型定义与您的问题定义略有不同。 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
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      相关资源
      最近更新 更多