我有以下格式的多个数据框
t1,t2,t3
p1, 1, 2, 3
p2, 1, 2, 3
我想将它们转换为
tests,obs
p1, t1, 1
p1, t2, 2
p1, t3, 3
p2, t1, 1
p2, t2, 2
p2, t3, 3
这样做的一般方法是什么? (我怎么走相反的方向?)
答案 0 :(得分:3)
这是基础R的另一种选择。
## Some sample data
mydf <- data.frame(t1 = c(1, 1), t2 = c(2, 2), t3 = c(3, 3),
row.names = c("p1", "p2"))
mydf
# t1 t2 t3
# p1 1 2 3
# p2 1 2 3
## Wide to long
out <- cbind(rn = rownames(mydf), stack(mydf))
out
# rn values ind
# 1 p1 1 t1
# 2 p2 1 t1
# 3 p1 2 t2
# 4 p2 2 t2
# 5 p1 3 t3
# 6 p2 3 t3
## Long back to wide
reshape(out, direction = "wide", idvar="rn", timevar="ind")
# rn values.t1 values.t2 values.t3
# 1 p1 1 2 3
# 2 p2 1 2 3
在长到宽的版本中,您必须将行名称放回row.names
并重命名列,如果您想要输入的确切版本。
如果列不是您的数据的一部分,则使用“reshape2”执行相同的操作,但rownames
就像它们在此处一样,或者按照Underminer建议的列添加它们,或者使用{{1}这将自动处理事情。
melt(as.matrix(.))
基地R的另一个选择当然是library(reshape2)
## Wide to long
out <- melt(as.matrix(mydf))
out
# Var1 Var2 value
# 1 p1 t1 1
# 2 p2 t1 1
# 3 p1 t2 2
# 4 p2 t2 2
# 5 p1 t3 3
# 6 p2 t3 3
## Long to wide
dcast(out, Var1 ~ Var2, value.var="value")
# Var1 t1 t2 t3
# 1 p1 1 2 3
# 2 p2 1 2 3
(有些人喜欢避免)。要使用reshape
,reshape
必须是rownames
中的列。
data.frame
如果您使用mydf$p <- rownames(mydf)
out <- reshape(mydf, direction = "long", idvar="p",
varying = c("t1", "t2", "t3"), sep = "")
out
# p time t
# p1.1 p1 1 1
# p2.1 p2 1 1
# p1.2 p1 2 2
# p2.2 p2 2 2
# p1.3 p1 3 3
# p2.3 p2 3 3
制作长格式,并且需要返回宽格式,则无需指定其他参数,因为它们作为属性存储到结果对象中。你可以使用:
reshape
如果您需要手动指定要从长到宽重塑的参数,它看起来像:
reshape(out)
答案 1 :(得分:2)
让我们的数据集dat
看起来像:
p t1 t2 t3
1 p1 1 2 3
2 p2 1 2 3
然后
library(reshape2)
dat.m <- melt(dat, id.vars = "p")
结果
p variable value
1 p1 t1 1
2 p2 t1 1
3 p1 t2 2
4 p2 t2 2
5 p1 t3 3
6 p2 t3 3
然后您可以按照您想要的任何列进行排序。