簡體   English   中英

列比較的交叉列表

[英]Cross tabulation from column comparisons

我有一個數據框,希望從該數據框之間進行每列值之間的成對比較。 最終,我旨在獲得比較的交叉表,其中每個值代表比較列中樣本之間相似度的百分比。 對於復制品以及到目前為止我嘗試過的東西:

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以獲取相應的百分比值。 我不確定我是否會以錯誤的方式進行操作,但是任何輸入都會受到贊賞

你可以試試:

 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   -

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM