user2805568
user2805568

Reputation: 297

which rows match a given vector in R

I have a matrix A,

A = as.matrix(data.frame(col1 = c(1,1,2,3,1,2), col2 = c(-1,-1,-2,-3,-1,-2), col3 = c(2,6,1,3,2,4)))

And I have a vector v,

v = c(-1, 2)

How can I get a vector of TRUE/FALSE that compares the last two columns of the matrix and returns TRUE if the last two columns match the vector, or false if they don't?

I.e., If I try,

A[,c(2:3)] == v

I obtain,

           col2  col3
[1,]  TRUE FALSE
[2,] FALSE FALSE
[3,] FALSE FALSE
[4,] FALSE FALSE
[5,]  TRUE FALSE
[6,] FALSE FALSE

Which is not what I want, I want both columns to be the same as vector v, more like,

result = c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE)

Since the first, and 5th rows match the vector v entirely.

Upvotes: 0

Views: 91

Answers (4)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Here's another straightforward option:

which(duplicated(rbind(A[, 2:3], v), fromLast=TRUE))
# [1] 1 5

results <- rep(FALSE, nrow(A))
results[which(duplicated(rbind(A[, 2:3], v), fromLast=TRUE))] <- TRUE
results
# [1]  TRUE FALSE FALSE FALSE  TRUE FALSE

Alternatively, as one line:

duplicated(rbind(A[, 2:3], v), fromLast=TRUE)[-(nrow(A)+1)]
# [1]  TRUE FALSE FALSE FALSE  TRUE FALSE

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61154

Here's a simple alternative

> apply(A[, 2:3], 1, function(x) all(x==v))
[1]  TRUE FALSE FALSE FALSE  TRUE FALSE

Upvotes: 1

albifrons
albifrons

Reputation: 305

A dirty one:

result <- c()
for(n in 1:nrow(A)){result[n] <-(sum(A[n,-1]==v)==2)}

> result
[1]  TRUE FALSE FALSE FALSE  TRUE FALSE

Upvotes: 0

user2805568
user2805568

Reputation: 297

Ooops by looking into R mailing list I found an answer: https://stat.ethz.ch/pipermail/r-help/2010-September/254096.html,

check.equal <- function(x, y)
{
  isTRUE(all.equal(y, x, check.attributes=FALSE))
}

result = apply(A[,c(2:3)], 1, check.equal, y=v)

Not sure I need to define a function and do all that, maybe there are easier ways to do it.

Upvotes: 1

Related Questions