2014-09-13 122 views
0

我有一个数据框,我希望在每个列的值之间进行配对比较。最终,我的目标是获得比较的交叉制表,其中每个值代表比较列中样本之间的相似性百分比。对于复制和我迄今尝试:来自列比较的交叉表

a <- c(1:30) 
b <- c(30:1) 
c <- c(1:10,30:11) 
data <- as.data.frame(matrix(c(a,b,c), ncol = 3, nrow = 30)) 

fr<-apply(combn(1:length(data), 2), 2, function(x) { 
result <- as.data.frame(table(
    factor(sign(data[,x[1]] - data[,x[2]]), levels=c(0), labels=c("Fr")) 
)) 
colnames(result)[1] <- paste(x, collapse="|") 
return(result) 
}) 
fr # returns a list of each comparison, with its respective similarity count 

a<-sapply(fr, unlist) # My attempt to get a dataframe/matrix of the results 
t(a) 

    t(a); sapply(fr, unlist); do.call(cbind, fr) # I get different arrangements, but none in the form: 

    1|2  0 
    1|3  10 
    2|3  0 

有一次,我在该格式得到数据帧,它会变得更加直截了当地得到一个交叉表,

 V.1 V.2 V.3 
V.1 - 
V.2 0 - 
V.3 10 0 - 

这是我最终会寻找,尽管交叉表中的值将是#/nrow以获得相应的百分比值。我不知道如果我要对这个错误的方式,但任何输入,将不胜感激

回答

2

你可以试试:

Cmbn <- combn(seq_along(data),2) 
nm1 <- apply(Cmbn, 2, paste, collapse="|") 

f1 <- setNames(
      apply(Cmbn, 2, function(x) { 
       x1 <- sign(data[,x[1]]- data[,x[2]]) 
       table(factor(x1, levels=0, labels="Fr")) #not sure why you wanted a label "Fr" as it didn't appear in the results 
          }), 
           nm1) 

    f1 
    #1|2 1|3 2|3 
    #0 10 0 


names1 <- paste("V", 1:3, sep=".") 
m1 <- matrix(0, 3,3, dimnames=list(names1, names1)) 
m1[paste(col(m1), row(m1), sep="|") %in% names(f1)] <- f1 
d1 <- as.data.frame(m1) 
d1[upper.tri(d1, diag=TRUE)] <- "-" 
d1 
# V.1 V.2 V.3 
#V.1 - - - 
#V.2 0 - - 
#V.3 10 0 - 
+1

'combn'有一个'FUN'参数,所以你也可以做' (combn(seq_along(data),2,FUN = function(x)table(factor(sign(data [,x [1]] - data [,x [2]]),levels = 0,labels = paste( x [1],x [2],sep =“|”))),simplify = FALSE))'到达“f1”。 – A5C1D2H2I1M1N2O1R2T1 2014-09-13 18:46:37

+0

@Ananda Mahto感谢您的评论 – akrun 2014-09-14 03:53:17