如何融合数据框中选定的单个列

时间:2016-01-22 03:13:17

标签: r reshape melt

使用此代码:

dat <- structure(list(Probes = structure(1:6, .Label = c("1415670_at",
"1415671_at", "1415672_at", "1415673_at", "1415674_a_at", "1415675_at"
), class = "factor"), Genes = structure(c(2L, 1L, 4L, 5L, 6L,
3L), .Label = c("Atp6v0d1", "Copg1", "Dpm2", "Golga7", "Psph",
"Trappc4"), class = "factor"), FOO = c(1.133, 1.068,
1.01, 0.943, 1.048, 1.053)), .Names = c("Probes", "Genes", "FOO"
), row.names = c(NA, 6L), class = "data.frame")

我创建了以下数据框:

        Probes    Genes   FOO
1   1415670_at    Copg1 1.133
2   1415671_at Atp6v0d1 1.068
3   1415672_at   Golga7 1.010
4   1415673_at     Psph 0.943
5 1415674_a_at  Trappc4 1.048
6   1415675_at     Dpm2 1.053

我想要做的是选择最后一列并将其融化为:

FOO 1.133 
FOO 1.068 
FOO 1.010 
FOO 0.943 
FOO 1.048 
FOO 1.053

我该怎么做?

我坚持使用这段代码:

library(reshape2)
melt(dat[,ncol(dat)])

1 个答案:

答案 0 :(得分:3)

我们可以在选择&#39; FOO&#39;后使用stack。列。

stack(dat['FOO'])

或者

melt(dat['FOO'])

dat[,'FOO']不是data.frame。这是vector。我们可以在[中找到[[?Extract等之间的差异。如果只有一列,则[的默认选项为drop=TRUE。如果我们使用drop=FALSE指定行索引,我们可以指定,

stack(dat[, "FOO", drop=FALSE])

如果我们不知道列名,请使用ncol

stack(dat[ncol(dat)])

不同之处在于我们如何使用它以及返回的对象。