R 编程.数据帧和子集



仅从数据帧中选择唯一集这里一组=一行数据框。R中的语法?我想要集合概念请参阅此示例

1 1 2
1 2 1
1 2 3

o/p:

1 1 2
1 2 3

这里 row1 和 row2 构成了sets ={1,2},所以我只需要这些行的一个副本。

这是我的先验算法代码。函数 trim(data,r( 是我一直在尝试作为解决方案,但没有解决。


uniqueItemSets<-function(data){
    #unique items in basket
    items <- c()
        for(j in c(1:ncol(data))){
            items <- c(items,unique(data[,j]))      
        }
        items <- unique(items)
    #return(as.list(items))
    return(items)
}
F_itemset<-function(data,candidate,sup){
    count <- rep(0,nrow(candidate))
    for(i in c(1:nrow(data))){          #every transaction
        for(j in c(1:nrow(candidate))){ #every dataset
            x <- candidate[j,]
            #x <- uniqueItemSets(x)
            y <- data[i,]
            #y <- uniqueItemSets(y)     
            if(all(x %in% y)){
                count[j] <- count[j] + 1
            }
        }       
    }
    #pruning
    pp<-cbind(candidate,count)
    pp<-as.data.frame(pp)
      pp<-subset(pp,pp$count>=sup)
    return(pp)
}
#k-itemset :k-value
makeItemSet<- function(candidate,k){
    l<-combn(candidate,k,simplify=FALSE)
    return(l)
} 
aprio<-function(data,sup,conf,kmax){
    C <- uniqueItemSets(data)
    C <- as.data.frame(C)
    for(k in c(2:kmax))
    {
        F <- F_itemset(data,C,sup)
        F$count <- NULL
        if(nrow(F)<k){
            break;
        }
        F<-t(F)
        C <- combn(F,k,simplify=FALSE)
        C <- as.data.frame(C)
        C <- t(C)   #transpose
        C<-unique(C)
        trim(C,1)
    }
    return(F)
}

**

new <- data.frame()
trim<-function(data,r)
{
    x<-as.data.frame(data[r,])
    c<-c()
    for(j in c(1:ncol(x))){
        c<-c(c,x[,j])
    }
    c<-unique(c)
    if(r+1<=nrow(data)){
    for(i in c((r+1):nrow(data))){
        t<-c()
        for(j in c(1:ncol(data))){
            t<-c(t,data[i,j])
        }
        t<-unique(t)
        if(all(t %in% c) && all(c %in% t))
        {
            data[-i,]
        }
    }
    new <- as.data.frame(data)
    if(r+1 < nrow(data)){
        trim(data[r+1:nrow(data),],r+1)
    }
    }
}

**

您可以将applymargin = 1一起使用来执行按行函数。唯一需要注意的是,您需要转置结果才能获得所需的订单

d <- data.frame(number1 = c(1,1,1),
                number2 = c(1,2,2),
                number3 = c(2,1,3))
# next two statements can be run in one line of code if you want
d_sort <- t(apply(d, 1, sort))
# get rid of duplicate rows
unique(d_sort)
     [,1] [,2] [,3]
[1,]    1    1    2
[2,]    1    2    3

最新更新