2014-01-06 34 views
1

我有以下形式的數據幀:檢索基於值的矩陣的特定條目從數據幀

my.df = data.frame(ID=c(1,2,3,4,5,6,7), STRAND=c('+','+','+','-','+','-','+'), COLLAPSE=c(0,0,1,0,1,0,0)) 

和尺寸的另一種基質由nrow(my.df)nrow(myDF上)。這是一個相關矩陣,但這對討論並不重要。

例如:

mat = matrix(rnorm(n=nrow(my.df)*nrow(my.df),mean=1,sd=1), nrow = nrow(my.df), ncol=nrow(my.df)) 

的問題是如何檢索僅從矩陣墊上部三角形元件,使得my.df具有COLLAPSE == 0的值,和是的相同鏈的?

在該具體實例,我會感興趣的檢索在載體從矩陣墊輸入以下內容:

mat[1,2] 
mat[1,7] 
mat[2,7] 
mat[4,6] 

的邏輯如下,1,2-都是相同鏈的,它的崩潰值等於零,所以應該檢索,3將永遠不會與任何其他行合併,因爲它具有崩潰值= 1,1,3是相同的鏈並具有崩潰值= 0,因此也應該檢索,.. 。

我可以寫一個for循環,但我正在尋找一種更奇特的方式來實現這樣的結果...

回答

2

這裏有一個辦法做到這一點使用outer

首先,找到具有相同STRAND價值指數和其中COLLAPSE == 0

idx <- with(my.df, outer(STRAND, STRAND, "==") & 
       outer(COLLAPSE, COLLAPSE, Vectorize(function(x, y) !any(x, y)))) 

#  [,1] [,2] [,3] [,4] [,5] [,6] [,7] 
# [1,] FALSE TRUE FALSE FALSE FALSE FALSE TRUE 
# [2,] TRUE FALSE FALSE FALSE FALSE FALSE TRUE 
# [3,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE 
# [4,] FALSE FALSE FALSE FALSE FALSE TRUE FALSE 
# [5,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE 
# [6,] FALSE FALSE FALSE TRUE FALSE FALSE FALSE 
# [7,] TRUE TRUE FALSE FALSE FALSE FALSE FALSE 

二,下三角和對角到FALSE設定值。創建一個數字索引:

idx2 <- which(idx & upper.tri(idx), arr.ind = TRUE) 
#  row col 
# [1,] 1 2 
# [2,] 4 6 
# [3,] 1 7 
# [4,] 2 7 

提取值:

mat[idx2] 
# [1] 1.72165093 0.05645659 0.74163428 3.83420241 
+0

不錯,+1。我似乎已經忘記了上部三... – Henrik

+0

@Sven Hohenstein,不錯,它的作品完美。 – Dnaiel

1

下面是做到這一點的方法之一。

# select only the 0 collapse records 
sel <- my.df$COLLAPSE==0 

# split the data frame by strand 
groups <- split(my.df$ID[sel], my.df$STRAND[sel]) 

# generate all possible pairs of IDs within the same strand 
pairs <- lapply(groups, combn, 2) 

# subset the entries from the matrix 
lapply(pairs, function(ij) mat[t(ij)]) 
1
df <- my.df[my.df$COLLAPSE == 0, ] 
strand <- c("+", "-") 
idx <- do.call(rbind, lapply(strand, function(strand){ 
    t(combn(x = df$ID[df$STRAND == strand], m = 2)) 
})) 
idx 
#  [,1] [,2] 
# [1,] 1 2 
# [2,] 1 7 
# [3,] 2 7 
# [4,] 4 6 

mat[idx]