繁体   English   中英

将矩阵与 r 中的向量进行比较时如何返回匹配行的索引

[英]How to return the index of the matching row when comparing a matrix to a vector in r

数据是:

a <- matrix(c(1,1,2,2,'a','b','c','d'),4,2)
b <- c(1,'a')

因此,第一排a匹配b 如果我想返回矩阵a中行的索引(即 1),我将在 r 中应用什么代码? 我试过:

which((a[,1]==b[1])&(a[,2]==b[2])), is there any other option?

我们可以通过 'a' 的row复制 'b' 并进行元素比较,然后包装which以获得索引

which(a == b[row(a)])

请注意,这给出了元素的索引。 如果我们需要所有匹配的行的索引。

which(rowSums(a == b[col(a)]) == ncol(a))

或者

 which(a == b)

另一种选择,但match

match(list(b),asplit(a,1))

或者

match(asplit(t(b),1),asplit(a,1))

或者

match(as.data.frame(t(t(b))),as.data.frame(t(a)))

更多选项:

which(colSums(t(a) != b) == 0)

which(rowSums(sweep(a, 2, b, `!=`)) == 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM