首页 > 解决方案 > 遍历行,查找具有匹配索引的匹配字符,如果是这样:在另一列中放入“1” - R

问题描述

我想遍历 'standard' & 'superficial.match' 并获得两位额外的数据:

1) 'standard' 是否有一个字符与'superficial.match' 中的字符具有相同的值和相同的索引('mips' = 就地匹配)

2) 'standard' 中有多少个字符与 'superficial.match' ('two.match') 中的字符匹配

例如:

在第 1 行中,第三位有一个匹配的 4,并且 'standard' 中有两个 4,所以 'mips' 和 '2match' 应该 = True 或 1

在第 6 行,有 4 个匹配,但只有 1 个匹配,所以 'mips' = True 和 'two.match' = False

> head.matrix(masterdata[c(5,6,14,15)], n=6)
  standard superficial.match mips two.match
1      464               584    0      0
2      575               159    0      0
3      686               896    0      0
4      131               971    0      0
5      818               348    0      0
6      242               348    0      0

第 3 行似乎有 1 个匹配的字符和 1 个不匹配的字符,这应该是 'mips' 的 'NA'

标签: rregexloopsfor-loopif-statement

解决方案


如果您拆分每个字段standardsuperficial.match获得其组成字符的向量,则可以将每一对与通常的==运算符进行比较。

我假设这些字段是字符串,而不是数字。

此函数进行拆分,检查匹配发生的位置数是否大于 0,然后,对于每个匹配的字符,检查它在standard列中出现的次数,如果匹配数 >=,则返回布尔值2.

fn <- function(x) {
  x1 <- unlist(strsplit(x[1], ''))
  x2 <- unlist(strsplit(x[2], ''))
  cmp <- x1 == x2
  mips <- sum(cmp) > 0
  if (mips) {
    two.match <- max(rowSums(outer(x1[cmp], x1, FUN = '=='))) >= 2  
  } else {
    two.match <- FALSE
  }

  c(mips = mips, two.match = two.match)
}

您可以在矩阵上逐行运行它x,然后转置为列格式:

t(apply(x, 1, fn))
      mips two.match
[1,]  TRUE      TRUE
[2,] FALSE     FALSE
[3,]  TRUE      TRUE
[4,]  TRUE      TRUE
[5,]  TRUE      TRUE
[6,]  TRUE     FALSE

推荐阅读