2017-06-18 23 views
1

的覆蓋我有以下幾點:最少數量清單

dist<-c('att1','att2','att3','att4','att5','att6') 
p1<-c('att1','att5','att2') 
p2<-c('att5','att1','att4') 
p3<-c('att3','att4','att2') 
p4<-c('att1','att2','att3') 
p5<-c('att6') 

我想找到所有相關p是他們的統一將是dist的最大組成部分。 我這種情況下的解決方案將是p1, p3, p5。 我想選擇p的最小數量。另外,如果無法覆蓋所有的dist組件,所以我想選擇最大覆蓋。

+0

爲什麼只有'P1,P3,p5'?是不是'p2,p3,p5'也是一樣的? – Sotos

+0

謝謝@索托斯,你是對的。在這種情況下,由於p1和p2具有相同數量的屬性,因此它也可以是解決方案。對我來說,一個解決方案就足夠好了(我不必全部獲得),只有滿足約束條件的第一個解決方案才行。 – Avi

回答

1

這是我的嘗試解決方案。我已儘可能多地嘗試矢量化/預測速度足夠快。每一步都在評論

library(qdapTools) 
library(dplyr) 
library(data.table) 
## generate matrix of attributes 
grid_matrix <- do.call(CJ, rep(list(1:0), 5)) %>% as.matrix 
attribute_matrix 
## att1 att2 att3 att4 att5 att6 
## 1 1 1 0 0 1 0 
## 2 1 0 0 1 1 0 
## 3 0 1 1 1 0 0 
## 4 1 1 1 0 0 0 
## 5 0 0 0 0 0 1 

## create a grid of combination of matrix 
grid_matrix <- do.call(CJ, rep(list(1:0), 5)) %>% as.matrix 
colnames(grid_matrix) <- paste0("p", 1:5) 

## check whether each combination has all attribute presented 
combin_all_element_present <- rowSums(grid_matrix %*% attribute_matrix > 0) %>% 
    `==`(., ncol(attribute_matrix)) 

combin_all_element_present 
## [1] TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE 
## [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 
## [23] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 

## generate a submatrix which satisfy the condition 
grid_matrix_sub <- grid_matrix[combin_all_element_present, ] 
## find the combinations with minumun number of p 
grid_matrix_sub[rowSums(grid_matrix_sub) == min(rowSums(grid_matrix_sub)), ] 
##  p1 p2 p3 p4 p5 
## [1,] 0 1 0 1 1 
## [2,] 0 1 1 0 1 
## [3,] 1 0 1 0 1 

註解釋

在要使用quanteda情況下,可以產生與attribute_matrix

library(quanteda) 
attribute_matrix <- lapply(list(p1, p2, p3, p4, p5), function(x) paste(x, collapse = ' ')) %>% 
    unlist %>% tokens %>% dfm %>% as.matrix 
attribute_matrix 
##  features 
## docs att1 att5 att2 att4 att3 att6 
## text1 1 1 1 0 0 0 
## text2 1 1 0 1 0 0 
## text3 0 0 1 1 1 0 
## text4 1 0 1 0 1 0 
## text5 0 0 0 0 0 1 
+0

謝謝我得到以下錯誤:> attribute_matrix < - lapply(list(p1,p2,p3,p4,p5),function(x)paste(x,collapse =''))%>% + unlist%>%令牌%>%dfm%>%as.matrix 有效對象(.Object)中的錯誤: 無效的類「dfmSparse」對象:在對象類的環境中未定義超類「replValueSp」 – Avi

+0

嗯。它應該是'quanteda'的版本問題。你的版本是什麼? –

+0

> packageVersion(「quanteda」) [1]'0.9.9.65'。我安裝了Matrix軟件包,現在我的錯誤是Error in validObject(.Object): 無效的類「dfmSparse」對象:在對象類的環境中未定義超類「replValueSp」 – Avi