r - 遍历行,查找具有匹配索引的匹配字符,如果是这样:在另一列中放入“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'
解决方案
如果您拆分每个字段standard
并superficial.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
推荐阅读
- r - 如何随时避免这种情况(
) “参考更新”? - reactjs - 无法读取 null 的属性 - react.js 状态
- python-3.x - 使用 Zelle graphics.py 将点逐一更新到窗口
- javascript - 用户自己可以为他们的 RichEmbed 设置描述吗
- python - 如何在 Django Rest Framework 中加入 3 个表(仅主键)
- ios - 在 Swift 中关闭应用程序时徽章图标不更新
- css - 如何在不旋转图像的情况下旋转剪辑路径?
- php - Apache/PHP 无法在 Ampps 中启动
- javascript - 将函数式 js 函数转换为一般情况
- ruby-on-rails - 如何在 capistrano 的 deploy.rb 文件中使用 Rails 5.2 凭据?