简体   繁体   中英

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?

If we are comparing elementwise, then convert 'A' to matrix , check whether the elements are %in% B, convert the logical vector to matrix , get the row index with which/arr.ind=TRUE and based on that find the row names.

row.names(A)[unique(which(`dim<-`(as.matrix(A) %in% B, dim(A)), arr.ind=TRUE)[,1])]
#[1] "b" "d"

Or if we are comparing corresponding columns in 'A' and 'B', we can do with mapply , get the rowSums , check whether it is 2 and find the row names based on that index.

row.names(A)[rowSums(mapply(function(x,y) x %in% y, A, as.data.frame(B)))==2]

Or we can paste the columns together and compare

row.names(A)[do.call(paste, A) %in% paste(B[,1], B[,2])]
#[1] "b" "d"

NOTE: All these methods are based on base R

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"

Another method you can try in base R

row.names(A)[A[,1] %in% B[,1] & A[,2] %in% B[,2]]
[1] "b" "d"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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