4

如何使用行名和列名转换以下矩阵(或表/数据框),

    A       B
M   27143   18324
F   29522   18875

变成类似的东西

27143  M  A
18324  M  B
29522  F  A
18875  F  B

以便我可以在 R 中进行一些分析?

4

2 回答 2

9

您可以使用reshape2包和melt数据。

temp = read.table(header=TRUE, text="    A       B
M   27143   18324
F   29522   18875")
library(reshape2)
temp$id = rownames(temp)
melt(temp)
# Using id as id variables
# id variable value
# 1  M        A 27143
# 2  F        A 29522
# 3  M        B 18324
# 4  F        B 18875
于 2012-07-16T17:26:03.093 回答
1

您还可以使用data.table将行名添加为第一列,然后根据行名将其融化

df<- structure(list(A = c(27143L, 29522L), B = c(18324L, 18875L)), .Names = c("A", 
"B"), class = "data.frame", row.names = c("M", "F"))

library(data.table)
library(reshape2)
setDT(df, keep.rownames = TRUE)[]

#   rn     A     B
#1:  M 27143 18324
#2:  F 29522 18875

(melt(df, id.vars="rn"))
#   rn variable value
#1:  M        A 27143
#2:  F        A 29522
#3:  M        B 18324
#4:  F        B 18875

gather改用melt

library(tidyr)
gather(df, "rn")
#  rn rn value
#1  M  A 27143
#2  F  A 29522
#3  M  B 18324
#4  F  B 18875
于 2016-12-31T09:52:23.260 回答