简体   繁体   English

用Wlidcard分组成对矩阵

[英]Subsetting a pairwise matrix with wlidcard

I would like to subset part of a large pairwise matrix into smaller matrices. 我想将大的成对矩阵的一部分子集化为较小的矩阵。 eg 例如

    TF1 TF2 TF3 TG1 TG2 TG3
TF1 0    2   1  450 460 450
TF2 2    0   1  452 462 462
TF3 1    2   0  451 461 451
TG1 450 452 450 0   2   0
TG2 460 462 462 2   0   1
TG3 450 452 451 1   2   0

I can subset if I input the exact column and row name "TF1" etc but I want eg all of the TFs. 如果我输入了确切的列名和行名“ TF1”等,则可以进行子集设置,但是我想要所有的TF。

I reckon it may be a grep but I cant put grep anywhere in my forumula: 我认为这可能是grep,但我无法在论坛中的任何地方放置grep:

TF <-T_PW[c("TF1","TF2","TF3"),c("TF1","TF2","TF3")]

This is the expected output matrix: 这是预期的输出矩阵:

    TF2 TF3 TF1   
TF1 0   2   1
TF2 2   0   1
TF3 1   2   0

Is it because since it is a pairwise then the columns and rows have names?? 是因为因为它是成对的,所以列和行才有名称?

Thank you 谢谢

grep returns the indices of the input that match the regex provided: grep返回与提供的正则表达式匹配的输入索引:

> grep('^TF', rownames(T_PW))
[1] 1 2 3

> grep('^TF', colnames(T_PW))
[1] 1 2 3

You can therefore place grep inside [] to subset the rownames and colnames of the matrix: 因此,您可以将grep内部[]到子集rownamescolnames矩阵:

TF = T_PW[grep('^TF', rownames(T_PW)), grep('^TF', colnames(T_PW))]

Since the rownames are symmetric to the colnames , you can also do something like this: 由于rownames是对称的colnames ,你也可以做这样的事情:

TF_names = grep('^TF', colnames(T_PW))

T_PW[TF_names, TF_names]

Result: 结果:

    TF1 TF2 TF3
TF1   0   2   1
TF2   2   0   1
TF3   1   2   0

Data: 数据:

T_PW = read.table(text="    TF1 TF2 TF3 TG1 TG2 TG3
TF1 0    2   1  450 460 450
                 TF2 2    0   1  452 462 462
                 TF3 1    2   0  451 461 451
                 TG1 450 452 450 0   2   0
                 TG2 460 462 462 2   0   1
                 TG3 450 452 451 1   2   0", header = TRUE, row.names=1)

T_PW = as.matrix(T_PW)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM