我想只得到矩阵A中的行,矩阵B中只有5个或任何4个数字。是否有可以用来解决它的R函数?
ΜatrixA
1 2 3 4 5
2 3 5 6 7
3 5 7 8 1
2 7 5 4 3
矩阵B:
1 2 4 5 6
2 4 1 3 7
3 5 7 9 8
5 8 9 2 6
如果我要求B中的5个数字匹配A中的行,我将得不到匹配的行。
如果我要求B中的4个数字匹配A中的行,我将得到:
B1 - A1
B2 - A1, A4
B3 - A3
答案 0 :(得分:1)
我不知道内置于R中的任何内容都可以使用,但这个自定义功能可以帮助您获得所需的内容。
find.matches <- function(A, B, num.matches){
# Set rownames for the matrix
rownames(A) = paste0(deparse(substitute(A)), 1:nrow(A))
rownames(B) = paste0(deparse(substitute(B)), 1:nrow(B))
# Create matrix indicating matching items
out <- t(apply(cbind(seq_len(nrow(B)),B), 1,
function(y) {
cur.b = y[-1]
res <- apply(cbind(seq_len(nrow(A)),A), 1,
function(z) {
cur.a = z[-1]
ifelse(sum(table(cur.a[cur.a %in% cur.b])) == num.matches, rownames(A)[z[1]], NA)})}))
# Create list of matching items
out <- apply(out, 1, function(x) paste(x[!is.na(x)]))
# Remove non matches from list
out <- out[lapply(out,length) > 0]
if(length(out) > 0){
# Convert list to a vector
out <- paste0(names(out), " - ", lapply(c(out), paste, collapse = ", "))
# Print the vector
cat(out, sep = "\n")
} else{
print("No Matches Found")
}
}
# Create matrices to compare
A <- matrix(c(1,2,3,2,2,3,5,7,3,5,7,5,4,6,8,4,5,7,1,3), nrow = 4)
B <- matrix(c(1,2,3,5,2,4,5,8,4,1,7,9,5,3,9,2,6,7,8,6), nrow = 4)
# Compare matrices
find.matches(A, B, 4)