Search code examples
rdataframematrixsubset

I have a subset matrix extracted from a data frame, how can I get the corresponding row names?


A=data.frame(Lat=(1:5),long=(6:10))
rownames(A)<-c("a","b","c","d","e")
B=matrix(c(2,7,4,9),nrow=2,ncol=2, byrow=TRUE)

How can I get the corresponding row names "b" and "d" for matrix B from data frame A?


Solution

  • You can use the function row.match in the package prodlim, which is very easy to use. It returns a vector with the row numbers of (first) matches and NA otherwise. You can use that vector (m in this example) to identify the rownames of A for which a match was found in B.

    library(prodlim)
    m <- row.match(A, B)
    rownames(A)[!is.na(m)]
    #[1] "b" "d"