簡體   English   中英

創建列之間的成對比較矩陣

[英]Create a matrix of pairwise comparisons between columns

我想創建一個矩陣,顯示每個成對列比較的行差異數。 這就是我要開始的:

     Ind1 Ind2 Ind3
Att1    A    A    B
Att2    A    C    C
Att3    B    B    D

這就是我想要結束的:

      Ind1  Ind2  Ind3
Ind1            
Ind2    1       
Ind3    3     2 

如何在 Python 或 R 中執行此操作?

試試下面adist

> adist(sapply(df, toString))
     Ind1 Ind2 Ind3
Ind1    0    1    3
Ind2    1    0    2
Ind3    3    2    0

您可以嘗試以下方法

df <- read.table(header = TRUE, text = "     Ind1 Ind2 Ind3
Att1    A    A    B
Att2    A    C    C
Att3    B    B    D")

v <- apply(combn(1:ncol(df), 2), 2, function(k) sum(df[, k[1]] != df[, k[2]]))
M <- matrix(0, nrow = ncol(df), ncol = ncol(df))
M[lower.tri(M)] <- v
M

     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    0    0
[3,]    3    2    0

利用:

arr = df.values.T
arr = np.sum(arr[:, None] != arr, axis = -1)
mask = np.triu(np.ones(arr.shape)) == 0
arr = np.where(mask, arr, np.nan)

>>> pd.DataFrame(data = arr, index = df.columns, columns = df.columns)
      Ind1  Ind2  Ind3
Ind1   NaN   NaN   NaN
Ind2   1.0   NaN   NaN
Ind3   3.0   2.0   NaN

另一種基本的 R 方法:

x <- combn(df, 2, function(x)sum(do.call("!=", x)))

attributes(x) <- list(Labels = names(df), Size = ncol(df), class = "dist")

x
     Ind1 Ind2
Ind2    1     
Ind3    3    2

如果你願意,你可以這樣做:

as.matrix(x)
     Ind1 Ind2 Ind3
Ind1    0    1    3
Ind2    1    0    2
Ind3    3    2    0

1) sapply在指示的 function 上執行雙sapply 我們可以有選擇地使用 as.dist 並在后面顯示的其他替代方案上類似地使用,但不會對每個都重復它。

nc <- ncol(m)
res <- sapply(1:nc, function(i) sapply(1:nc, function(j) sum(m[, i] != m[, j])))

res
##      [,1] [,2] [,3]
## [1,]    0    1    3
## [2,]    1    0    2
## [3,]    3    2    0

或者

as.dist(res)
##   1 2
## 2 1  
## 3 3 2

2) 列表理解使用 eList package 我們可以像這樣生成它:

library(eList)

nc <- ncol(m)
Mat(for(i in 1:nc) for(j in 1:nc) sum(m[, i] != m[, j]))
##      [,1] [,2] [,3]
## [1,]    0    1    3
## [2,]    1    0    2
## [3,]    3    2    0

3)外部我們可以像這樣使用outer

f <- function(i, j) sum(m[, i] != m[, j])
outer(1:nc, 1:nc, Vectorize(f))
##      [,1] [,2] [,3]
## [1,]    0    1    3
## [2,]    1    0    2
## [3,]    3    2    0

筆記

m <- structure(c("A", "A", "B", "A", "C", "B", "B", "C", "D"), .Dim = c(3L, 
3L), .Dimnames = list(c("Att1", "Att2", "Att3"), c("Ind1", "Ind2", 
"Ind3")))

暫無
暫無

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

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