2015-08-31 36 views
2

我正在做Fisher的排列測試,其中我必須生成所有治療狀態的組合。使用矩陣值作爲指標

我們有4個科目,其中2個被處理。使用combn,我可以生成治療科目的所有組合。例如,第一行意味着第一個和第二個主題被處理。

t(combn(4, 2)) 

    [,1] [,2] 
[1,] 1 2 
[2,] 1 3 
[3,] 1 4 
[4,] 2 3 
[5,] 2 4 
[6,] 3 4 

如何從這個矩陣去的處理狀態的矩陣如下:

 [,1] [,2] [,3] [,4] 
[1,] 1 1 0 0 
[2,] 1 0 1 0 
... 
+2

這可以使用在''combn' +的'FUN'選項來完成(t(下combn(4,2,FUN =函數(x)的1:%×4%)))' – akrun

+0

@ akrun的評論實際上效果最好(即最容易理解)。 (你可以把它作爲答案?)heroka的答案可能有一個小錯字,因爲我得到錯誤。 MichaelChirico的答案是最快的。 – Heisenberg

+0

我以@ akrun's和他爲基準進行了基準測試,光速更快(對於20選擇10,速度更快3000倍)。 – MichaelChirico

回答

3

發佈作爲溶液我的意見。這是@ Heroka建議的修改。 +將把logical轉換爲numeric,並且應該比as.integer更快。

+(t(combn(4,2, FUN=function(x) 1:4 %in% x))) 
#  [,1] [,2] [,3] [,4] 
#[1,] 1 1 0 0 
#[2,] 1 0 1 0 
#[3,] 1 0 0 1 
#[4,] 0 1 1 0 
#[5,] 0 1 0 1 
#[6,] 0 0 1 1 
6

使用基地-R:

res <- t(apply(t(combn(4,2)),MARGIN=1,FUN=function(x){ 
    return(as.numeric(1:4 %in% x)) 
})) 
> res 
    [,1] [,2] [,3] [,4] 
[1,] 1 1 0 0 
[2,] 1 0 1 0 
[3,] 1 0 0 1 
[4,] 0 1 1 0 
[5,] 0 1 0 1 
[6,] 0 0 1 1 
+0

繼@ @ akrun在'combn'中提出了'FUN'的建議,並從'%x'的'1:4%'中獲得靈感,我認爲這是最簡單的答案:'t(combn(4,2,FUN = function ){return(as.numeric(1:4%in%x))}))' – Heisenberg

+0

'as.integer'應該更快。 – MichaelChirico

5

如何只:

out <- matrix(0L, nrow = nrow(x), ncol = max(x)) 

for (i in 1:nrow(x)) out[i, x[i, ]] <- 1L 

> out 
    [,1] [,2] [,3] [,4] 
[1,] 1 1 0 0 
[2,] 1 0 1 0 
[3,] 1 0 0 1 
[4,] 0 1 1 0 
[5,] 0 1 0 1 
[6,] 0 0 1 1 

我們也可以做到這一點沒有循環,雖然它可能是一個小的可讀性(感謝@Frank爲步法):

m <- matrix(0L, choose(4, 2), 4) 
m[cbind(rep(1:choose(4, 2), each = 2), c(combn(4, 2)))] <- 1L 

容易裹入的函數:

participants <- function(m, n){ 
    if (n > m) stop() 
    mcn <- choose(m, n) 
    out <- matrix(0L, mcn, m) 
    out[cbind(rep(1:mcn, each = n), c(combn(m, n)))] <- 1L 
    out 
} 

> participants(6, 5) 
    [,1] [,2] [,3] [,4] [,5] [,6] 
[1,] 1 1 1 1 1 0 
[2,] 1 1 1 1 0 1 
[3,] 1 1 1 0 1 1 
[4,] 1 1 0 1 1 1 
[5,] 1 0 1 1 1 1 
[6,] 0 1 1 1 1 1 
+2

你可以使用(1)'choose'來獲取組合數量和(2)矩陣賦值而不是循環:'m < - matrix(0L,choose(4,2),4); m [cbind(rep(1:choose(4,2),each = 2),c(combn(4,2)))] < - 1L'。同樣的想法。 – Frank