I am trying to gregexpr search for the locations of "ABCD" in a large string and "ABBD, ACCD, AAAD" in the same string. I want to output the "ABCD" search results and the "ABBD, ACCD, AAAD" search results in two separate columns of a data table.
My current approach is to use gregexpr separately, export each as a 1 column txt file, import each as matrices, sort each 1 column matrix so that the numbers ascend by row, column bind the two matrices, and convert the resulting two column matrix into a data table.
This approach seems to be highly inefficient when dealing with a extremely large string, and takes quite a while to complete. Is there any way to optimize the procedure? Thanks for your help!
# dummy string that is relatively short for this demo
x <- "ABCDACCDABBDABCDAAADACCDABBDABCD"
# SEARCH for 'ABCD' location
out1 <- gregexpr(pattern = "ABCD", x)
cat(paste(c(out1[[1]]), sep = "\n", collapse = "\n"), file = "~/out_1.txt")
# SEARCH for 'A??D' location
outB <- gregexpr(pattern = "ABBD", x)
outC <- gregexpr(pattern = "ACCD", x)
outA <- gregexpr(pattern = "AAAD", x)
cat(paste(c(outA[[1]], outB[[1]], outC[[1]]), collapse = "\n"), file = "~/out_2.txt")
# Function that BINDS Matrices by column
cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x) rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
# Load as Tables --> Sort by numbers increasing --> Matrices
mat1 <- as.matrix(read.table("~/out_1.txt"))
mat2.t <- (read.table("~/out_2.txt"))
mat2 <- as.matrix(mat2.t[order(mat2.t$V1),])
# Combine two matrices to create 2 column matrix
comb_mat <- cbind.fill(mat1, mat2)
write.table(comb_mat, file = "~/comb_mat.txt", row.names = FALSE, col.names = FALSE)