check whether matrix rows equal a vector in R , vectorized

前端 未结 3 521
刺人心
刺人心 2021-01-17 22:06

I\'m very surprised this question has not been asked, maybe the answer will clear up why. I want to compare rows of a matrix to a vector and return whether the row == the v

相关标签:
3条回答
  • The package prodlim has a function called row.match, which is easy to use and ideal for your problem. First install and load the library: library(prodlim). In our example, row.match will return '5' because the 5th row in M is equal to v. We can then convert this into a logical vector.

    m <- row.match(v, M)
    m==1:NROW(M)#[1] FALSE FALSE FALSE FALSE  TRUE
    
    0 讨论(0)
  • 2021-01-17 22:55

    One possibility is

    rowSums(M == v[col(M)]) == ncol(M)
    ## [1] FALSE FALSE FALSE FALSE  TRUE
    

    Or simlarly

    rowSums(M == rep(v, each = nrow(M))) == ncol(M)
    ## [1] FALSE FALSE FALSE FALSE  TRUE
    

    Or

    colSums(t(M) == v) == ncol(M)
    ## [1] FALSE FALSE FALSE FALSE  TRUE
    

    v[col(M)] is just a shorter version of rep(v, each = nrow(M)) which creates a vector the same size as M (matrix is just a vector, try c(M)) and then compares each element against its corresponding one using ==. Fortunately == is a generic function which has an array method (see methods("Ops") and is.array(M)) which allows us to run rowSums (or colSums) on it in order to makes sure we have the amount of matches as ncol(M)

    0 讨论(0)
  • 2021-01-17 22:59

    Using DeMorgan's rule (Not all = Some not), then All equal = Not Some Not equal, we also have

    !colSums(t(M) != v)
    
    0 讨论(0)
提交回复
热议问题