在R的一列中排序单词列表

时间:2018-03-22 13:06:07

标签: r apply sapply arules

我有apriori的输出数据框,规则如下:

rules
{A,B} => {C}
{C,A} => {B}
{A,B} => {D}
{A,D} => {B}
{A,B} => {E}
{E,A} => {B}

我得到它直到这一点,我在每个规则中对项目进行分组(data.frame是df_basket)

rules           basket
{A,B} => {C}    A,B,C
{C,A} => {B}    C,A,B
{A,B} => {D}    A,B,D
{A,D} => {B}    A,D,B
{A,B} => {E}    A,B,E
{E,A} => {B}    E,A,B

我希望能够按字母顺序订购购物篮,如下所示:

rules           basket  Group
{A,B} => {C}    A,B,C   A,B,C
{C,A} => {B}    C,A,B   A,B,C
{A,B} => {D}    A,B,D   A,B,D
{A,D} => {B}    A,D,B   A,B,D
{A,B} => {E}    A,B,E   A,B,E
{E,A} => {B}    E,A,B   A,B,E

我使用下面的代码可以很好地处理小数据帧并完成工作。对于大数据帧,for循环效率低下。请帮我在R:

中优化这个原子操作
for(i in 1:nrow(df_basket))
{
  df_basket$Basket[i]<- ifelse(1==1,paste(unlist(strsplit(df_basket$basket[i],","))
                                          [order(unlist(strsplit(df_basket$basket[i],",")))],collapse=","))

} 

如果有任何简单或更直接的信息,请告诉我数据框的“群组”字段。

2 个答案:

答案 0 :(得分:2)

尝试调整此解决方案:

f<-function(x)
{
  sorted<-sort(unlist(strsplit(x,",")))
  return(paste0(sorted,collapse = ","))

}
cbind(basket,unlist(lapply(basket,f)))

输入数据:

basket<-c("A,B,C","C,A,B","A,B,D","A,D,B","A,B,E","E,A,B")

输出:

     basket         
[1,] "A,B,C" "A,B,C"
[2,] "C,A,B" "A,B,C"
[3,] "A,B,D" "A,B,D"
[4,] "A,D,B" "A,B,D"
[5,] "A,B,E" "A,B,E"
[6,] "E,A,B" "A,B,E"

答案 1 :(得分:1)

以下是使用arules的更多支持的另一种方式:

### create some random data and mine rules
library("arules")
dat <- replicate(10, sample(LETTERS[1:5], size = 3), simplify = FALSE)
trans <- as(dat, "transactions")
rules <- apriori(trans)
inspect(rules)

    lhs      rhs support confidence lift     count
[1] {}    => {A} 0.8     0.8        1.000000 8    
[2] {B}   => {A} 0.6     1.0        1.250000 6    
[3] {C,D} => {E} 0.2     1.0        1.428571 2    
[4] {B,D} => {A} 0.1     1.0        1.250000 1    
[5] {B,C} => {A} 0.2     1.0        1.250000 2    
[6] {B,E} => {A} 0.3     1.0        1.250000 3   

### Get the itemsets that generated each rule and convert the itemsets 
### into a list. I use a list, since in gerneral, rules will not all 
### have the same number of items.
itemsets <- as(items(generatingItemsets(rules)), "list")

### sort the item labels alphabetically. Note that you could already 
### start with the item labels correctly sorted in the transaction set
### (see manual page for itemcoding in arules).
lapply(itemsets, sort)

[[1]]
[1] "A"

[[2]]
[1] "A" "B"

[[3]]
[1] "C" "D" "E"

[[4]]
[1] "A" "B" "D"

[[5]]
[1] "A" "B" "C"

[[6]]
[1] "A" "B" "E"

如果所有规则具有相同数量的项目,则可以将此列表放入矩阵中。

如果您想将它们作为单个字符串,则可以执行以下操作:

sapply(lapply(itemsets, sort), paste0, collapse = ",")
[1] "A"     "A,B"   "C,D,E" "A,B,D" "A,B,C" "A,B,E"