library(dplyr)
## Demo --
## Target Matrix ----
MatTar <- matrix(c(1:3,
                2:3, 1,
                3, 1:2,
                12,3:4), 4, 3, byrow = T)
MatTar
## Data Matrix ----
N <- 1e+5
P <- 3
set.seed(2022)
MatData <- matrix(sample(1:36, size = N*P, replace = T), N ,P)
MatData[1:6,] # first 6 rows


## Vector-String approach
MatTar_to_Vec <- MatTar %>% apply(X = ., MARGIN = 1, FUN = function(X) as.character(list(as.character(X))))
MatTar_to_Vec

idx_1  <- MatData %>% 
  apply(X = ., MARGIN = 1, FUN = function(X) as.character(list(as.character(X)))) %>% 
  is.element(., MatTar_to_Vec) %>% which


## Paste_locka approach ----
MatTar_to_Vec <- MatTar %>% apply(X = ., MARGIN = 1, FUN = function(X) paste(X, collapse = ""))
MatTar_to_Vec

idx_2 <- MatData %>% 
  apply(X = ., MARGIN = 1, FUN = function(X) paste(X, collapse = "")) %>% 
  is.element(., MatTar_to_Vec) %>% which

## Vectorize_and_Wush978 approach ----
idx_3  <- MatData %>% apply(X = ., MARGIN = 1, FUN = function(X) prod(colSums(abs(X - t(MatTar))))== 0 ) %>% which


## Result ----
dimnames(MatData) <-  list(paste("Row",1:N), paste("Col",1:P))
# Demo_1
print('Demo_1')
idx_1 %>% '['(MatData, .,)
# Demo_2
print('Demo_2')
idx_2 %>% '['(MatData, .,)
print('Demo_3')
# Demo_3
idx_3 %>% '['(MatData, .,)


# 1.Some bugs in Demo_2 
## Row 18228     1     2    34
## Row 20352     1    23     4
## Row 62305     1     2    34

# 2.Demo_3: String matrix does NOT adapted

# 3.Demo_1: Better

## benchmark ----
# library(dplyr)
# library(ggplot2)
# library(microbenchmark)
# 
# MatTar <- matrix(c(1:3,
#                    2:3, 1,
#                    3, 1:2,
#                    12,3:4), 4, 3, byrow = T)
# N <- 1e+5
# P <- 3
# set.seed(2022)
# MatData <- matrix(sample(1:36, size = N*P, replace = T), N ,P)
# 
# mbm <- microbenchmark(
#   "Demo_1" = {
#     MatTar_to_Vec <- MatTar %>% apply(X = ., MARGIN = 1, FUN = function(X) as.character(list(as.character(X))))
#     
#     idx_1  <- MatData %>% 
#       apply(X = ., MARGIN = 1, FUN = function(X) as.character(list(as.character(X)))) %>% 
#       is.element(., MatTar_to_Vec) %>% which
#     
#   },
#   "Demo_2" = {
#     MatTar_to_Vec <- MatTar %>% apply(X = ., MARGIN = 1, FUN = function(X) paste(X, collapse = ""))
#     MatTar_to_Vec
#     
#     idx_2 <- MatData %>% 
#       apply(X = ., MARGIN = 1, FUN = function(X) paste(X, collapse = "")) %>% 
#       is.element(., MatTar_to_Vec) %>% which
#   },
#   "Demo_3" = {
#     idx_3  <- MatData %>% apply(X = ., MARGIN = 1, FUN = function(X) prod(colSums(abs(X - t(MatTar))))== 0 ) %>% which
#   },
#   times = 100
)
# mbm
# autoplot(mbm)

# mbm
# Unit: milliseconds
#    expr      min       lq     mean   median       uq       max neval
#  Demo_1 656.6060 696.4229 728.8200 728.2004 757.0074  857.5347   100
#  Demo_2 499.8685 585.9709 614.7522 617.6975 648.6348  758.6131   100
#  Demo_3 697.8651 867.4010 912.0625 934.6069 966.6985 1092.6792   100