首页 > 解决方案 > 无法在 R 中创建矩阵

问题描述

我使用以下方法读取 tsv 文件:

> dt <- read.table("gene.tsv", fill=TRUE, header=TRUE, quote="", sep="\t")

然后我检查我的数据>head(dt),我得到了这个:

 Gene Healthy_A Healthy_B Infected_A Infected_B
1  zwf        79        57         99        100
2 yyaP        99        99         99         99
3 xylB        74        45         78         99
4  hup        77        61         86         99
5  pgi        67        41         66         99
6  lon        98        76         99         99

我使用以下方法设置行名:

> rownames(dt) <- dt$gene

而不是使用我的数据制作一个矩阵:

> dt_matrix <- as.matrix(dt[2:5])

但是当我使用 检查矩阵时head(dt_matrix),我的数据如下所示:

Healthy_A Healthy_B Infected_A Infected_B
[1,]        79        57         99        100
[2,]        99        99         99         99
[3,]        74        45         78         99
[4,]        77        61         86         99
[5,]        67        41         66         99
[6,]        98        76         99         99

我希望我的矩阵看起来像下面创建热图:

 Gene       Healthy_A Healthy_B Infected_A Infected_B
  zwf        "79"        "57"         "99"        "100"
 yyaP        "99"        "99"         "99"         "99"
 xylB        "74"        "45"         "78"         "99"
  hup        "77"        "61"         "86"         "99"
  pgi        "67"        "41"         "66"         "99"
  lon        "98"        "76"         "99"         "99"

我怎样才能得到我想要的?

标签: r

解决方案


像这样创建矩阵后设置行名

dt <- fread(' Gene Healthy_A Healthy_B Infected_A Infected_B
  zwf        79        57         99        100
 yyaP        99        99         99         99
 xylB        74        45         78         99
  hup        77        61         86         99
  pgi        67        41         66         99
  lon        98        76         99         99')

dt_rownames <- dt$Gene

dt_matrix <- as.matrix(dt[,-1])
rownames(dt_matrix) <- dt_rownames
head(dt_matrix)

     Healthy_A Healthy_B Infected_A Infected_B
zwf         79        57         99        100
yyaP        99        99         99         99
xylB        74        45         78         99
hup         77        61         86         99
pgi         67        41         66         99
lon         98        76         99         99

推荐阅读