在向量元素中查找模式

Find pattern in elements of vectors

我有一些像

这样的载体
A1 = c(A,B,C)
A2 = c(A,B,C)
A3 = c(A,B,NA)
A4 = c(NA,B,C)

现在我想要一些能给我结果的东西:

Pattern (A,B,C) occurs 2 times.
Pattern (A,B) occurs 3 times.
Pattern (B,C) occurs 3 times.

现在我对每个向量进行比较。通过这种方式,我可以找到 A、B、C 模式,但找不到 A、B 或 B、C 模式。

是否有任何包或一些数学模型可以做到这一点?

编辑1: 由于某些机密性问题,我将无法 post 代码,但本质上我所做的是我将第一个向量与第二个向量进行比较,然后与第三个向量进行比较,依此类推,使用 %in%。它给了我一个真假矩阵。然后我对所有向量重复了这个过程。最后我发现 true 在矩阵中的最大密度。

编辑 2 : 我知道 a-priori 算法和 arules 包,但 a-priori 不是很有效。

它可能会变得更短,但这是一种方法:

A1 = c("A","B","C")
A2 = c("A","B","C")
A3 = c("A","B", NA)
A4 = c(NA,"B","C")

a <- lapply(list(A1, A2, A3, A4), function(x){
   x[is.na(x)] <- " "
   paste0(x, collapse="")
})

pattern <- c("B", "C")
pattern_2 <- paste0(pattern, collapse="")

sum(sapply(a, function(x){grepl(pattern_2, x)}))

一个非常糟糕的方法(很多循环)。它接近您要找的东西。

library(combinat)

A1 = c("A","B","C")
A2 = c("A","B","C")
A3 = c("A","B", NA)
A4 = c(NA,"B","C")
df <- data_frame(A1, A2, A3, A4)
df[is.na(df)] <- " "

a <- sapply(1:dim(df)[1], function(x) {combn(unique(unlist(apply(df, 1, unique))), x)})

pattern <- unlist(lapply(a, function(x){
  apply(x, 2, function(y){paste0(y, collapse="_")})
}))

a <- lapply(list(A1, A2, A3, A4), function(x){
  x[is.na(x)] <- " "
  paste0(x, collapse="_")
})

df2 <- sapply(a, function(x){sapply(pattern, function(z){grepl(z, x)})})
pattern <- rownames(df2)

occurs <- apply(df2, 1, sum)
pattern <- gsub(" ", "NA", pattern)


pattern <- gsub("_", ", ", pattern)
# pattern <- strsplit(pattern, "_")

for(i in 1:length(pattern)){
  cat("Pattern (", pattern[[i]], ") occurs ", occurs[i], " times\n")
}