如何重新排列数据框,使一列中的值是行名?

How to rearrange data frame so that values in one column are row names?

我有一个包含大约 450K 甲基化 β 值的数据框。 450 个探针用于两个样品。此数据显示在三列中,如下所示:

>head(ICGC)
 submitted_sample_id    probe_id    methylation_value
1  X932-01-4D          cg00000029         0.6
2  X932-01-6D          cg00000029         0.4
3  X932-01-4D          cg00000108         0.3
4  X932-01-6D          cg00000108         0.7
5  X932-01-4D          cg00000109         0.9
6  X932-01-6D          cg00000109         0.1

我想重新排列这个 data.frame 以便探针 ID 是行名,样本 ID 是列名,这样它看起来像这样:

>head(ICGC_2)
           X932-01-4D    X932-01-6D 
cg00000029    0.6           0.4
cg00000108    0.3           0.7
cg00000109    0.9           0.1

我试过:

>library(tidyverse)
ICGC_2 <- ICGC %>% remove_rownames %>% column_to_rownames(var = "probe_id")

但这不起作用,因为 ICGC 中的每个探针 ID 在列中出现了两次(因为有两个样本)。我也试过:

hello <- data.frame(ICGC[,-2], row.names = ICGC[,2])

但这有同样的问题。我想以这种方式重新排列此数据的原因是因为我想将 beta 值转换为 M 值并将此数据用作 cpg.annotate 中的对象(可通过 Bioconductor 包 DMRcate 获得)- cpg.annotate 要求对象具有唯一的 Illumina 探针 ID 作为行名和唯一的样本 ID 作为列名。

谢谢!

你们很亲近。 spread 包中的 tidyr 函数正是您所需要的。

library(tidyverse)

ICGC_2 <- ICGC %>%
  spread(submitted_sample_id, methylation_value) %>%
  remove_rownames() %>%
  column_to_rownames(var = "probe_id")
ICGC_2
           X932-01-4D X932-01-6D
cg00000029        0.6        0.4
cg00000108        0.3        0.7
cg00000109        0.9        0.1

数据:

ICGC <- read.table(text = "submitted_sample_id    probe_id    methylation_value
1  'X932-01-4D'          cg00000029         0.6
2  'X932-01-6D'          cg00000029         0.4
3  'X932-01-4D'          cg00000108         0.3
4  'X932-01-6D'          cg00000108         0.7
5  'X932-01-4D'          cg00000109         0.9
6  'X932-01-6D'          cg00000109         0.1",
                   header = TRUE, stringsAsFactors = FALSE)

在 base R 中你可以这样做:

wICGC <- reshape(ICGC, idvar = "probe_id", 
                       timevar = "submitted_sample_id", direction = "wide")
wICGC <- data.frame(wICGC[,-1], row.names=wICGC[,1])

wICGC

#            methylation_value.X932.01.4D methylation_value.X932.01.6D 
# cg00000029                          0.6                          0.4 
# cg00000108                          0.3                          0.7 
# cg00000109                          0.9                          0.1

换个角度,也可以在reshape中使用melt

library(reshape)
m <- melt(IGC, id=c("submitted_sample_id", "probe_id"))
cast(m, probe_id~submitted_sample_id)

> cast(m, probe_id~submitted_sample_id)
    probe_id X932-01-4D X932-01-6D
1 cg00000029        0.6        0.4
2 cg00000108        0.3        0.7
3 cg00000109        0.9        0.1