列比较的交叉列表

时间:2014-09-13 15:35:03

标签: r

我有一个数据框,我想从中执行每列值之间的成对比较。最终,我的目标是获得比较的交叉列表,其中每个值表示比较列中样本之间的相似性百分比。对于复制和我到目前为止所尝试的内容:

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以获得相应的百分比值。我不确定我是否会以错误的方式解决这个问题,但任何意见都会受到赞赏

1 个答案:

答案 0 :(得分: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   -
相关问题