2017-01-27 8 views
1

私は、これは以前に回答されている、しかし、 は次のようになり、相関行列を与え知っている次のようにRにロードすることができ並び替え、行と列

V A B C  D 
A 1 0.3 0.1 0.4 
B 0.2 1 0.4 0.3 
C 0.1 0 1  0.9 
D 0.3 0.3 0.1 1 

corr.matrix <- read.table("path/to/file", sep = '\t', header = T) 
rownames(corr.matrix) <- corr.matrix$V 
corr.matrix <- corr.matrix[, 2:ncol(corr.matrix)] 

2つのファイルに基づいて、どの行と列をプロットするかを指定します(私には興味がないものもあるため)。2つのファイルがどのように記述されるかを行と列に並べ替える必要があります。

例えば

:私はこのようなものを、他の2つのファイルの読み取り

cols_order.txt      
C 
D 
E 
B 
A 
... 

rows.txt 
D 
E 
Z 
B 
T 
A 
... 

rows.order <- ("rows_order.txt", sep = '\n', header=F) 
colnames(rows.order) <- "Variant" 

cols.order <- ("cols_order.txt", sep = '\n', header=F) 
colnames(cols.order) <- "Variant" 

をし、このステップの後に、私はこれを行う:

corr.matrix <- corr.matrix[rows.order$Variant, cols.order$Variant] 

値Iドンプロットしようとしているのはうまく取り除かれていますが、その注文はスクランブルされてしまいます。これをどうすれば解決できますか?

.orderデータセットが正しく読み取られました(私は3回チェックしました)。

答えて

3

ここにあなたの質問に対する潜在的な解決策があります。私はあなたの質問に基づいて小さなdata.frameを再作成しようとしました。あなたはdplyrパッケージと構文に慣れている場合は、それを使用することができ、あるいは、

## Re-create your example: 
V <- data.frame(
    A = c(1 , 0.3, 0.1 , 0.4), 
    B = c(0.2, 1 , 0.4 , 0.3), 
    C = c(0.1, 0 , 1 , 0.9), 
    D = c(0.3, 0.3, 0.1 , 1) 
) #matrix() also ok 
rownames(V) <- LETTERS[1:4] 

## Reorder using `match` function 
## Needs to be in data.frame form 
## So use as.data.frame() if needed 

## Here, I don't have the text file 
## So if you want to load in txt files specifying rows columns 
## Use `read.csv` or `read.table to load 
## And then store the relevant info into a vector as you did 

col_order <- c("C","D","E","B","A") 
col_order_filtered <- col_order[which(col_order %in% colnames(V))] 
rows <- c("D","E","Z","B","T","A") 
## Filter rows IDs, since not all are present in your data 
row_filtered <- rows[rows %in% rownames(V)] 

V1 <- V[match(rownames(V), row_filtered), match(colnames(V), col_order_filtered)] 
V1 <- V1[-which(rownames(V1)=="NA"), ] 
V1 

##  D C A B 
## C 0.1 1.0 0.1 0.4 
## B 0.3 0.0 0.3 1.0 
## A 0.3 0.1 1.0 0.2 

と、多くの場合、それは便利です::ここで重要なのは、match機能だけでなく、Rにおけるいくつかの基本的なサブセット/フィルタリング技術をある

## Continued from previous code 
library(dplyr) 
V2 <- V %>% 
    select(C, D, B, A, everything()) %>% 
    slice(match(rownames(V), row_filtered)) 
rownames(V2) <- row_filtered 
V2 
##  C D B A 
## D 1.0 0.1 0.4 0.1 
## B 0.0 0.3 1.0 0.3 
## A 0.1 0.3 0.2 1.0 

希望するものがあります。