gpt4 book ai didi

r - 如何获得两个矩阵的交集?

转载 作者:行者123 更新时间:2023-12-04 12:13:06 25 4
gpt4 key购买 nike

# These are the two matrices that I would like to subset based on identical
# entries within entire rows.
mata <- matrix(c("A", "B", "C", "F", "D", "E", "F", "G"),
nrow = 4, ncol = 2,
dimnames = list(c(), c("A", "B")))
mata

## A B
## [1,] "A" "D"
## [2,] "B" "E"
## [3,] "C" "F"
## [4,] "F" "G"

matb <- matrix(c("B", "A", "C", "F", "M", "D", "D", "H", "G", "X"),
nrow = 5, ncol = 2,
dimnames = list(c(), c("A", "B")))
matb

## A B
## [1,] "B" "D"
## [2,] "A" "D"
## [3,] "C" "H"
## [4,] "F" "G"
## [5,] "M" "X"

如果两个矩阵不是无序的且长度相同,则以下代码应该可以工作并且效率很高。

mata[rowMeans(mata == matb) == 1, ]

我的一个骇人听闻的解决方案是连接个人我想用于匹配的每个矩阵的列。在这个示例我将使用所有列。

mata <- cbind(mata, C = paste0(mata[, "A"], "_", mata[, "B"]))
matb <- cbind(matb, C = paste0(matb[, "A"], "_", matb[, "B"]))
mata[mata[, "C"] %in% matb[, "C"], colnames(mata) != "C"]

## A B
## [1,] "A" "D"
## [2,] "F" "G"

这是我正在寻找的结果,但我想知道是否还有一些更优雅的东西,例如向量的 %in% 函数。

编辑

该解决方案应适用于矩阵不存在的一般情况必须等长。

最佳答案

您可以为此使用函数 merge():

> merge(mata,matb)
A B
1 A D
2 F G

关于r - 如何获得两个矩阵的交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com